socket.io send packet to sender only

后端 未结 3 689
暗喜
暗喜 2021-01-30 18:16

I have yet to figure out how to directly respond to only the sender using socket.io

I have learned that io.sockets.emit sends to all clients but I wont to send informati

3条回答
  •  太阳男子
    2021-01-30 18:52

    When your server listens, you usually get a socket at the "connection" event :

    require('socket.io').on('connect', function(socket){
    

    A socket connects 2 points : the client and the server. When you emit on this socket, you emit to this specific client.

    Example :

    var io = require('socket.io');
    io.on('connect', function(socket){
        socket.on('A', function(something){
            // we just received a message
            // let's respond to *that* client :
            socket.emit('B', somethingElse);
        });
    });
    

    Be careful that those are two different calls :

    • socket.emit : emit to just one socket
    • io.sockets.emit : emit to all sockets

提交回复
热议问题