node.js socket.io How to emit to a particular client?

醉酒当歌 提交于 2021-02-05 12:56:08

问题


I want to "emit" a message to a particular client which is selected based on another message received in a different client, How do I do this?

I am thinking of joining each client to their own "room" and then broadcast. Is there a better way?


回答1:


UPDATE for socket.io version 1.0 and above

io.to(socketid).emit('message', 'whatever');

For older version:

You can store each client in an object as a property. Then you can lookup the socket based on the message:

var basket = {};

io.sockets.on('connection', function (socket) {
  socket.on("register", function(data) {
    basket[data.nickname] = socket.id;
  });
  socket.on("privmessage", function(data){
    var to = basket[data.to];
    io.sockets.socket(to).emit(data.msg);
  });
});

Not tested...but it should give you an idea




回答2:


For socket.io version 1.0 use:

io.to(socketid).emit('message', 'whatever');



回答3:


Emitting to a particular client using a socketID.

Server/ package: socket.io:

io.to(socketID).emit('testEvent', 'yourMessage');

Client/ package socket.io-client:

io.sockets.on('connection',(socket) => {
  socket.on("testEvent", data => {
    console.log(data);
  });
});

You can get access the socketID in the following manner:

io.on('connection', (socket, next) => {
    const ID = socket.id // id property on the socket Object
})

It is simply a property on the socket object




回答4:


For socket.io v1.0< use:

io.to(socketID).emit('testEvent', 'yourMessage');



来源:https://stackoverflow.com/questions/10110411/node-js-socket-io-how-to-emit-to-a-particular-client

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