SquishyAura
SquishyAura

Reputation: 43

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.

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.

Upvotes: 0

Views: 382

Answers (2)

SquishyAura
SquishyAura

Reputation: 43

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.

Upvotes: 0

Aierto
Aierto

Reputation: 48

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

Upvotes: 0

Related Questions