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

后端 未结 4 1652
后悔当初
后悔当初 2021-01-30 14:48

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 joinin

4条回答
  •  一向
    一向 (楼主)
    2021-01-30 15:13

    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

提交回复
热议问题