Sending data only to chosen users using Socket.io-node

偶尔善良 提交于 2020-01-06 05:47:25

问题


Is it possible to send data using socket.io-node just to chosen group of users? For example, how could I implement chat with different rooms? I dont want .broadcast() to send data to all logged in users.


回答1:


Normally you should have for each room a list of connected user and those user all have a client object that you should have stored somewhere. So when you want to send a message to a specific room, you just have to iterate over the connected user of that room and access their client object and send the data.

In short, it is possible you just have to send your data to each of the users in the group one-by-one.




回答2:


socket.io has a grouping functionality built in

On the socket object for a single connection, like you get passed when a new user connects, you can call .join('roomName') where roomName is any string you want to use to identify the "room", you could use a room name like "profile/14" to create a channel for updates to user #14's profile.

Then on the main io object do something like:

io.sockets.in('profile/14').emit('newComment', {message:'hello'});

The message will go out to all connections that have .join()'d the given room.

Typically I'll have my client emit a "hello" event onConnect that identifies what content the client is interested in subscribing to, and then on the server side my handler for the "hello" event handles .join()'ing the client into whatever rooms are needed



来源:https://stackoverflow.com/questions/4943573/sending-data-only-to-chosen-users-using-socket-io-node

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