Socket.io rooms difference between broadcast.to and sockets.in

前端 未结 5 2184
囚心锁ツ
囚心锁ツ 2020-12-02 05:43

Socket.io\'s readme contains the following example:

    var io = require(\'socket.io\').listen(80);

    io.sockets.on         


        
5条回答
  •  醉梦人生
    2020-12-02 05:55

    Update 2019: socket.io is a special module which uses websockets and then fallsback to http request polling. For just websockets: for the client use native websockets and for node.js use ws or this library.

    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);
    

提交回复
热议问题