0

I'm trying to build a private messaging app using socket.io. My assumption was that per session there would only ever be one socket.id. If i keep track of my socket.id and console.log it, it's constantly chnaging and I dont know why.

Here a snippet if how I am saving a new user.

//Listen on the connection for incoming sockets

io.on('connection',function (socket) {
console.log(socket.id)

    //Add the users to the socket session
    socket.on("add-user", function(username){
        oCurrentUser = {
            username: username,
            id: socket.id
        };
        console.log("socket.id for this user is", oCurrentUser.id);
        aClients.push(oCurrentUser);
        console.log(aClients);
        socket.emit('login',oCurrentUser);
    });
    });

Response after I create a users:

listening on *:3000

Vws9v-Wegjx4bvBKAAAA

e611mmTgdYmFvhuMAAAB

IPE95tFpgem0eyvyAAAC

m5YLVR0PE_Qqc-AcAAAD

GXbyRVYAnHgBz4VzAAAE

When I do console.log(socket.id) is get like 5 ID's. I would of assumed it would return just one right?

Phil Dimeski
  • 41
  • 1
  • 7
  • If you drop a breakpoint in the 'connection' handler is it called multiple times? from my reading of the socket io docs it should have a unique id per socket – shaunhusain Nov 18 '17 at 05:39
  • For some reason breakpoints are not triggering in my server.js file. But I have placed a console log inside the connection and it seems to display multiple ID's. – Phil Dimeski Nov 18 '17 at 06:11
  • A given connection has exactly one `socket.id`. It is not clear where the console you show is coming from since nothing in the code you show would create that console listing. `console.log(socket.id)` will only show one id. `socket.id` is a single string property. If you're seeing five, then that line of code is apparently getting called 5 times. You don't show where that line of code is so we can't really advise further on that output. – jfriend00 Nov 18 '17 at 08:20
  • 1
    `aClients.push(oCurrentUser);` may just be accumulating incoming sockets forever if you aren't also removing sockets from that list when they disconnect. You do not have to maintain your own list of connected sockets because socket.io does that for you and you can get that list from socket.io at any time. – jfriend00 Nov 18 '17 at 08:20
  • My bad I forgot to add that, the console log is us beneath the 'io.on('connection',function (socket)'. I am using UI-router for route between components could this cause a disconnect/reconnect for a session. This issue is stopping me from messaging individual clients or even rooms cause I cant access the correct socket.id as there are multiple. – Phil Dimeski Nov 18 '17 at 23:25
  • use authentication middleware which allow only one socket per session – shivshankar Nov 19 '17 at 07:42

0 Answers0