Wednesday, 15 March 2017

Socket.IO emitting for each client when only one client emits

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.



via SquishyAura

No comments:

Post a Comment