Socket.io odaları, broadcast.to ve sockets.in arasındaki fark


102

Socket.io'nun benioku dosyası aşağıdaki örneği içerir:

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

Arasındaki fark nedir socket.broadcast.to()ve io.sockets.in()?


14
örnek veriler için olumlu oy verin
dave

Yanıtlar:


122

socket.broadcast.toverilen odadaki tüm soketlere yayın yaparken çağrıldığı soket dışında , verilen odadaki io.sockets.intüm soketlere yayın yapar.


1
bir kanal bir odadan ne şekilde farklıdır?
vsync

6
hiçbirinde. Aynı şey için farklı isim.
mike_hornbeck

socket.io, kanal yerine oda terimini kullanır. Odalar / kanallar socket.io'daki ad alanları ile karıştırılmamalıdır. Doğru terimi kullanmak için cevabımı güncelledim.
Daniel Baulig

40

Node.js gerçekten ilgilendiğim bir şeydi ve bunu projemden birinde çok oyunculu bir oyun yapmak için kullandım.

io.sockets.in().emit()ve socket.broadcast.to().emit()Socket.io'nun Odalarında kullandığımız başlıca iki yayma yöntemidir ( https://github.com/LearnBoost/socket.io/wiki/Rooms ) Odalar, bağlı istemcilerin basit bir şekilde bölümlenmesine izin verir. Bu, olayların bağlı istemci listesinin alt kümelerine gönderilmesine izin verir ve bunları yönetmek için basit bir yöntem sağlar.

Bağlantılı istemci listesinin (oda dediğimiz) alt kümelerini yönetmemize ve ana socket.io işlevleri gibi benzer işlevlere sahip olmamıza io.sockets.emit()ve socket.broadcast.emit().

Her neyse, açıklamak için yorumlarla örnek kodlar vermeye çalışacağım. Yardımcı olup olmadığına bakın;

Socket.io Odaları

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

    }
}

Şerefe


35

2019 Güncellemesi : socket.io websockets kullanan ve ardından http istek yoklamasına geri dönen özel bir modüldür. Yalnızca web soketleri için: istemci için yerel web soketlerini ve node.js için ws veya bu kitaplığı kullanın.

Basit örnek

Sözdizimi socketio'da kafa karıştırıcıdır. Ayrıca, her soket kimlik ile kendi odalarına otomatik olarak bağlanır socket.id(bu, socketio'da özel sohbet böyle çalışır, odaları kullanırlar).

Gönderene gönder, başka kimseye

socket.emit('hello', msg);

Gönderen dahil (gönderen odada ise) "odam" odasındaki herkese gönder

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

"Odam" odasındaki gönderen dışındaki herkese gönder (gönderen odada ise)

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

Herkese gönder her odada , dahil gönderici

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

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

Yalnızca belirli bir sokete gönder (özel sohbet)

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

Nasıl bulmak için otherSocket.id . onu nereye kurmalı?
Iman Marashi

@ImanMarashi Tek yapmanız gereken diğer soket nesnesini almak ve sonra onun id özelliğine erişmek. otherSocket.on('connect',()=> { console.log(otherSocket.id); });
basickarl

Harika! io.to ('odam']. emit ('merhaba', msg); bana yardım et :)
iamkdblue

@ImanMarashi, otherSocket.id'i dışarıdaki bir dizi veya nesneye kaydedersiniz. Ve daha sonra çağrılan soketten erişin.
basickarl

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

};

Koda eşlik edecek bir açıklama sağlayabilir misiniz? Genellikle sadece kod sağlamak hoş karşılanmaz. Ancak, kodunuzun iyi yorumlanmış olduğunu görebiliyorum :)
MBorg

Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.