socket.io send packet to sender only

后端 未结 3 685
暗喜
暗喜 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:43

    Simple example

    The syntax is confusing in socketio. Also, every socket is automatically connected to their own room with the id socket.id (this is how private chat works in socketio, they use rooms).

    Send to the sender and noone else

    socket.emit('hello', msg);
    

    Send to everyone including the sender(if the sender is in the room) in the room "my room"

    io.to('my room').emit('hello', msg);
    

    Send to everyone except the sender(if the sender is in the room) in the room "my room"

    socket.broadcast.to('my room').emit('hello', msg);
    

    Send to everyone in every room, including the sender

    io.emit('hello', msg); // short version
    
    io.sockets.emit('hello', msg);
    

    Send to specific socket only (private chat)

    socket.broadcast.to(otherSocket.id).emit('hello', msg);
    
    0 讨论(0)
  • 2021-01-30 18:44

    late but better than never ;)

    I had smth like this:

    io.on('connection', function(socket){
        socket.emit('some event', data);
        socket.on('private event', function(message){
            this.emit('other private event', message);
        }
    }
    

    After some testing, I realized that 'this.emit' inside 'private event' closure send back only to sender. So i tried 'this.broadcast.emit', which send the message to all connected except the sender. I believe this is what you want from your code.

    0 讨论(0)
  • 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
    0 讨论(0)
提交回复
热议问题