Diferencia de habitaciones socket.io entre broadcast.to y sockets.in


102

El archivo Léame de Socket.io contiene el siguiente ejemplo:

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

    io.sockets.on('connection', function (socket) {
      socket.join('justin bieber fans');
      socket.broadcast.to('justin bieber fans').emit('new fan');
      io.sockets.in('rammstein fans').emit('new non-fan');
    });

¿Cuál es la diferencia entre socket.broadcast.to()y io.sockets.in()?


14
voto positivo para los datos de ejemplo
— dave

Respuestas:


122

socket.broadcast.tose transmite a todos los enchufes de la habitación dada, excepto al enchufe en el que se llamó, mientras que se io.sockets.intransmite a todos los enchufes de la habitación dada.


1
¿En qué se diferencia un canal de una sala?
— vsync

6
en ninguno. Nombre diferente para lo mismo.
— mike_hornbeck

socket.io usa el término sala en lugar de canal. Sin embargo, las habitaciones / canales no deben confundirse con los espacios de nombres en socket.io. Actualicé mi respuesta para usar el término correcto.
— Daniel Baulig

40

Node.js era algo que realmente me interesó durante un tiempo y lo usé en uno de mis proyectos para hacer un juego multijugador.

io.sockets.in().emit()y socket.broadcast.to().emit()son los dos métodos de emisión principales que usamos en las habitaciones de Socket.io ( https://github.com/LearnBoost/socket.io/wiki/Rooms ) Las habitaciones permiten una partición simple de los clientes conectados. Esto permite que los eventos se emitan con subconjuntos de la lista de clientes conectados y proporciona un método simple para administrarlos.

Nos permiten administrar los subconjuntos de la lista de clientes conectados (que llamamos habitaciones) y tener funcionalidades similares como las funciones principales de socket.io io.sockets.emit()ysocket.broadcast.emit() .

De todos modos intentaré dar los códigos de ejemplo con los comentarios para explicar. Vea si ayuda;

Habitaciones Socket.io

i) io.sockets.in (). emit ();

/* Send message to the room1. It broadcasts the data to all 
   the socket clients which are connected to the room1 */

io.sockets.in('room1').emit('function', {foo:bar});

ii) socket.broadcast.to (). emit ();

io.sockets.on('connection', function (socket) {
    socket.on('function', function(data){

        /* Broadcast to room1 except the sender. In other word, 
            It broadcast all the socket clients which are connected 
            to the room1 except the sender */
        socket.broadcast.to('room1').emit('function', {foo:bar});

    }
}

Socket.io

i) io.sockets.emit ();

/* Send message to all. It broadcasts the data to all 
   the socket clients which are connected to the server; */

io.sockets.emit('function', {foo:bar});

ii) socket.broadcast.emit ();

io.sockets.on('connection', function (socket) {
    socket.on('function', function(data){

        // Broadcast to all the socket clients except the sender
        socket.broadcast.emit('function', {foo:bar}); 

    }
}

Salud


35

Actualización 2019 : socket.io es un módulo especial que usa websockets y luego recurre al sondeo de solicitud http. Solo para websockets: para el cliente, use websockets nativos y para node.js use ws o esta biblioteca.

Ejemplo simple

La sintaxis es confusa en socketio. Además, cada socket se conecta automáticamente a su propia habitación con la identificación socket.id(así es como funciona el chat privado en socketio, usan habitaciones).

Enviar al remitente y a nadie más

socket.emit('hello', msg);

Enviar a todos, incluido el remitente (si el remitente está en la sala) en la sala "mi sala"

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

Enviar a todos menos al remitente (si el remitente está en la sala) en la sala "mi sala"

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

Enviar a todos en cada habitación , incluido el remitente

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

io.sockets.emit('hello', msg);

Enviar solo a un socket específico (chat privado)

socket.broadcast.to(otherSocket.id).emit('hello', msg);

Cómo encontrar otherSocket.id . donde ponerlo?
— Iman Marashi

@ImanMarashi Todo lo que necesita hacer es obtener el otro objeto de socket y luego acceder a su propiedad id. otherSocket.on('connect',()=> { console.log(otherSocket.id); });
— K - La toxicidad en SO está aumentando.

Increíble ! io.to ('mi habitación'). emit ('hola', msg); me ayuda :)
— iamkdblue

@ImanMarashi guardas el otherSocket.id en una matriz u objeto afuera. Y acceda a él más tarde desde el socket que se llame.
— K - La toxicidad en SO está aumentando.

2
io.on('connect', onConnect);

function onConnect(socket){

  // sending to the client
  socket.emit('hello', 'can you hear me?', 1, 2, 'abc');

  // sending to all clients except sender
  socket.broadcast.emit('broadcast', 'hello friends!');

  // sending to all clients in 'game' room except sender
  socket.to('game').emit('nice game', "let's play a game");

  // sending to all clients in 'game1' and/or in 'game2' room, except sender
  socket.to('game1').to('game2').emit('nice game', "let's play a game (too)");

  // sending to all clients in 'game' room, including sender
  io.in('game').emit('big-announcement', 'the game will start soon');

  // sending to all clients in namespace 'myNamespace', including sender
  io.of('myNamespace').emit('bigger-announcement', 'the tournament will start soon');

  // sending to a specific room in a specific namespace, including sender
  io.of('myNamespace').to('room').emit('event', 'message');

  // sending to individual socketid (private message)
  io.to(`${socketId}`).emit('hey', 'I just met you');

  // WARNING: `socket.to(socket.id).emit()` will NOT work, as it will send to everyone in the room
  // named `socket.id` but the sender. Please use the classic `socket.emit()` instead.

  // sending with acknowledgement
  socket.emit('question', 'do you think so?', function (answer) {});

  // sending without compression
  socket.compress(false).emit('uncompressed', "that's rough");

  // sending a message that might be dropped if the client is not ready to receive messages
  socket.volatile.emit('maybe', 'do you really need it?');

  // specifying whether the data to send has binary data
  socket.binary(false).emit('what', 'I have no binaries!');

  // sending to all clients on this node (when using multiple nodes)
  io.local.emit('hi', 'my lovely babies');

  // sending to all connected clients
  io.emit('an event sent to all connected clients');

};

¿Puede proporcionar una explicación para acompañar el código? Generalmente, solo proporcionar código está mal visto. Sin embargo, puedo ver que su código está bien comentado :)
— MBorg

1

En Socket.IO 1.0, .to () y .in () son lo mismo. Y otros en la sala recibirán el mensaje. El cliente lo envía, no recibirá el mensaje.

Consulte el código fuente (v1.0.6):

https://github.com/Automattic/socket.io/blob/a40068b5f328fe50a2cd1e54c681be792d89a595/lib/socket.js#L173


Dado que .to()y ,inson lo mismo, entonces, ¿qué sucedería cuando creo una habitación con el mismo nombre exacto que la identificación de algún socket? ¿Qué haría entonces, socket.broadcast.to(socketid)por ejemplo?
— Gust van de Wal
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.