socket.io client to client messaging

2020-03-30 04:42发布

I'm having trouble getting basic client to client (or really client->server->client) working with socket.io. Heres the code I have right now:

io.sockets.on('connection', function (socket) {

users.push(socket.sessionId);

for(userID in users)    {
    console.log(userID);
    io.sockets.socket(userID).emit('message', { msg: 'New User Connected succesfully' });
}
socket.emit('message', { msg: 'Connected succesfully' });


socket.on('my other event', function (data) {
    console.log(data);
  });
});

From my understanding, that should send the new user message to every connected user (individually, since i want to do actual individual messages later). Instead, I only get the 'connected successfully' message at the end. I don't get any errors or other negative indicators from my server or client.

Any ideas of why io.sockets.socket(userID).emit() doesn't work or what to use in its place?

3条回答
\"骚年 ilove
2楼-- · 2020-03-30 04:54

You can now also use ...

io.to('room').emit('event_name', data);

as an alternative to io.sockets.in

查看更多
家丑人穷心不美
3楼-- · 2020-03-30 05:20

Try

users.push(socket); // without .sessionId

for (var u in users)    {
   // users[u] is now the socket
   console.log(users[u].id);
   users[u].emit('message', { msg: 'New User Connected succesfully' });
}
查看更多
The star\"
4楼-- · 2020-03-30 05:20

Socket.io has the concept of rooms where, once a socket has joined a room, it will receive all message sent to a room, so you don't need to track who's in the room, deal with disconnections, etc...

On connection, you'd use:

socket.join('room')

And to send a message to everyone in that room:

io.sockets.in('room').emit('event_name', data)

More info on the socket.io wiki: https://github.com/LearnBoost/socket.io/wiki/Rooms

查看更多
登录 后发表回答