0

I'm having this weird issue where when I emit a message to the server while there only is 1 client, everything works fine, as in only one message gets sent. But when more than one clients are connected to the server, and one client emits something to the server, the server receives the message from every single client for some weird reason.

I'm using Socket.IO and Angular 2.

Client code:

import { Component } from '@angular/core';
import * as io from "socket.io-client";

@Component({
  moduleId: module.id,
  selector: 'register-app',
  templateUrl: 'register.component.html',
})
export class RegisterComponent  { name = 'Angular'; 
socket: SocketIOClient.Socket;
    constructor(){
        this.socket = io('http://localhost:9999');
    }

    registerAccount(){
        this.socket.emit('sweg', JSON.stringify('waaaaat'));
    }
}

Server code:

io.on('connect', function (socket) {
    console.log("a user connected");
    
    socket.on('sweg', function(msg) {
        var incomingMsg = JSON.parse(msg);
        console.log(incomingMsg);
    });
});

Server response when emitting with 1 client: image Server response when emitting with 2 clients: image

As you can see, the client is for some reason emitting twice, since there are 2 clients, even though only 1 of those clients decided to emit. Any help would be appreciated.

Edit: If I perhaps wasn't clear, my goal is that when a client emits, it should only emit for itself and not all the other clients.

Community
  • 1
  • 1
SquishyAura
  • 43
  • 2
  • 8

2 Answers2

0

Each Client Emits and connect to the server, therefore you will receive 2 messages in your server.

Aierto
  • 48
  • 7
  • Do you perhaps have a way to fix that. Not sure how to fix it myself unfortunately. My goal is that even though multiple clients connect, the one client that emits should actually be the only one that the server receives a message from. – SquishyAura Mar 16 '17 at 09:03
0

I found out what the issue was. The issue was related to Angular 2. If you type "http://localhost:3001/" in the url bar, Browsersync opens. Go to Sync Options and turn off "Clicks - mirrors clicks across devices". That solved it for me, hope it helps people that have this issue in the future.

SquishyAura
  • 43
  • 2
  • 8