Socket.io fa differenza tra broadcast.to e sockets.in


102

Il file readme di Socket.io contiene il seguente esempio:

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

Qual è la differenza tra socket.broadcast.to()e io.sockets.in()?


14
voto positivo per i dati di esempio
dave

Risposte:


122

socket.broadcast.totrasmette a tutte le prese nella stanza data, eccetto alla presa su cui è stato chiamato mentre io.sockets.intrasmette a tutte le prese nella stanza data.


1
in che modo un canale è diverso da una stanza?
vsync

6
in nessuno. Nome diverso per la stessa cosa.
mike_hornbeck

socket.io utilizza il termine room invece di channel. stanze / canali non devono essere confusi con i namespace in socket.io però. Ho aggiornato la mia risposta per utilizzare il termine corretto.
Daniel Baulig

40

Node.js era qualcosa a cui ero davvero interessato e l'ho usato in uno dei miei progetti per creare un gioco multiplayer.

io.sockets.in().emit()e socket.broadcast.to().emit()sono i due principali metodi di emissione che utilizziamo nelle stanze di Socket.io ( https://github.com/LearnBoost/socket.io/wiki/Rooms ) Le stanze consentono un semplice partizionamento dei client connessi. Ciò consente di emettere eventi con i sottoinsiemi dell'elenco dei client connessi e fornisce un metodo semplice per gestirli.

Ci permettono di gestire i sottoinsiemi della lista dei clienti collegati (che chiamiamo stanze) e hanno funzionalità simili come le funzioni principali di socket.io io.sockets.emit()e socket.broadcast.emit().

Comunque cercherò di fornire i codici di esempio con i commenti per spiegare. Vedi se aiuta;

Socket.io Rooms

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

    }
}

Saluti


35

Aggiorna 2019 : socket.io è un modulo speciale che utilizza websocket e poi fallisce nel polling delle richieste http. Solo per websocket: per il client usa websocket nativi e per node.js usa ws o questa libreria.

Semplice esempio

La sintassi è fonte di confusione in socketio. Inoltre, ogni socket è automaticamente connesso alla propria stanza con l'id socket.id(è così che funziona la chat privata in socketio, usano le stanze).

Invia al mittente e nessun altro

socket.emit('hello', msg);

Invia a tutti, incluso il mittente (se il mittente è nella stanza) nella stanza "la mia stanza"

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

Invia a tutti tranne il mittente (se il mittente è nella stanza) nella stanza "la mia stanza"

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

Invia a tutti in ogni stanza , incluso il mittente

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

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

Invia solo a socket specifico (chat privata)

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

Come trovare otherSocket.id . dove posizionarlo?
Iman Marashi

@ImanMarashi Tutto quello che devi fare è ottenere l'altro oggetto socket e quindi accedere alla sua proprietà id. otherSocket.on('connect',()=> { console.log(otherSocket.id); });
K - La tossicità in SO sta crescendo.

Eccezionale ! io.to ('la mia stanza'). emit ('ciao', msg); mi aiuta :)
iamkdblue

@ImanMarashi salvi l'altroSocket.id in un array o in un oggetto esterno. E accedervi in ​​un secondo momento da qualsiasi presa chiamata.
K - La tossicità in SO sta crescendo.

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

};

Potete fornire una spiegazione per accompagnare il codice? Generalmente solo fornire codice è disapprovato. Tuttavia, posso vedere che il tuo codice è ben commentato :)
MBorg

1

In Socket.IO 1.0, .to () e .in () sono gli stessi. E gli altri nella stanza riceveranno il messaggio. Il client lo invia non riceverà il messaggio.

Controlla il codice sorgente (v1.0.6):

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


Dato che .to()e ,insono la stessa cosa, allora cosa succederebbe quando creo una stanza con lo stesso identico nome dell'ID di un socket. Cosa farebbe, socket.broadcast.to(socketid)ad esempio, allora?
Gust van de Wal
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.