socket.io client to client messaging

百般思念 提交于 2019-12-30 11:47:12

问题


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?


回答1:


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' });
}



回答2:


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




回答3:


You can now also use ...

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

as an alternative to io.sockets.in



来源:https://stackoverflow.com/questions/15255969/socket-io-client-to-client-messaging

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!