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

后端 未结 4 1651
后悔当初
后悔当初 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 14:57

    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

提交回复
热议问题