Wyślij odpowiedź do wszystkich klientów oprócz nadawcy


226

Aby wysłać coś do wszystkich klientów, używasz:

io.sockets.emit('response', data);

Aby otrzymywać od klientów, używasz:

socket.on('cursor', function(data) {
  ...
});

Jak połączyć te dwa elementy, aby po otrzymaniu wiadomości na serwerze od klienta wysyłałem tę wiadomość do wszystkich użytkowników oprócz tego, który ją wysyła?

socket.on('cursor', function(data) {
  io.sockets.emit('response', data);
});

Czy muszę go zhackować, wysyłając identyfikator klienta z wiadomością, a następnie sprawdzając po stronie klienta, czy jest to łatwiejszy sposób?

Odpowiedzi:


840

Oto moja lista (zaktualizowana do wersji 1.0) :

// sending to sender-client only
socket.emit('message', "this is a test");

// sending to all clients, include sender
io.emit('message', "this is a test");

// sending to all clients except sender
socket.broadcast.emit('message', "this is a test");

// sending to all clients in 'game' room(channel) except sender
socket.broadcast.to('game').emit('message', 'nice game');

// sending to all clients in 'game' room(channel), include sender
io.in('game').emit('message', 'cool game');

// sending to sender client, only if they are in 'game' room(channel)
socket.to('game').emit('message', 'enjoy the game');

// sending to all clients in namespace 'myNamespace', include sender
io.of('myNamespace').emit('message', 'gg');

// sending to individual socketid
socket.broadcast.to(socketid).emit('message', 'for your eyes only');

// list socketid
for (var socketid in io.sockets.sockets) {}
 OR
Object.keys(io.sockets.sockets).forEach((socketid) => {});

14
Czy chcesz to wnieść do FAQ ? czy mogę to dla ciebie zrobić? (Podam tutaj link zwrotny)
Kos

1
Nie mam iotutaj. tylkosocket
chovy

2
Oprócz // sending to all clients except sendertego, do czego używać // sending a response to sender client only ?
Basj

4
Czy możesz dodać, że zgodnie z gniazdem # in , nadajesocket.to('others').emit('an event', { some: 'data' }); także w pokoju.
gongzhitaao

119
Jest to bardziej przydatne niż wszystko w połączeniu z dokumentami socket.io
Jonathan.

43

Z odpowiedzi @LearnRPG, ale z wersją 1.0:

 // send to current request socket client
 socket.emit('message', "this is a test");

 // sending to all clients, include sender
 io.sockets.emit('message', "this is a test"); //still works
 //or
 io.emit('message', 'this is a test');

 // sending to all clients except sender
 socket.broadcast.emit('message', "this is a test");

 // sending to all clients in 'game' room(channel) except sender
 socket.broadcast.to('game').emit('message', 'nice game');

 // sending to all clients in 'game' room(channel), include sender
 // docs says "simply use to or in when broadcasting or emitting"
 io.in('game').emit('message', 'cool game');

 // sending to individual socketid, socketid is like a room
 socket.broadcast.to(socketid).emit('message', 'for your eyes only');

Aby odpowiedzieć na komentarz @ Crashalot, socketidpochodzi z:

var io = require('socket.io')(server);
io.on('connection', function(socket) { console.log(socket.id); })

3
Niesamowite! Jak dostać socketidza wysłanie do pojedynczego gniazda?
Crashalot,

2
Edytowane z odpowiedzią na twoje pytanie. Zasadniczo pochodzi socket.idz obiektu gniazda.
soyuka

do wysyłania do osoby możesz użyć socket.emit, który ją wysyła, lub zgrupować połączonych klientów i zrobić @Crashalot
ujwal dhakal

12

Oto pełniejsza odpowiedź na temat zmian z wersji 0.9.x na 1.x.

 // send to current request socket client
 socket.emit('message', "this is a test");// Hasn't changed

 // sending to all clients, include sender
 io.sockets.emit('message', "this is a test"); // Old way, still compatible
 io.emit('message', 'this is a test');// New way, works only in 1.x

 // sending to all clients except sender
 socket.broadcast.emit('message', "this is a test");// Hasn't changed

 // sending to all clients in 'game' room(channel) except sender
 socket.broadcast.to('game').emit('message', 'nice game');// Hasn't changed

 // sending to all clients in 'game' room(channel), include sender
 io.sockets.in('game').emit('message', 'cool game');// Old way, DOES NOT WORK ANYMORE
 io.in('game').emit('message', 'cool game');// New way
 io.to('game').emit('message', 'cool game');// New way, "in" or "to" are the exact same: "And then simply use to or in (they are the same) when broadcasting or emitting:" from http://socket.io/docs/rooms-and-namespaces/

 // sending to individual socketid, socketid is like a room
 io.sockets.socket(socketid).emit('message', 'for your eyes only');// Old way, DOES NOT WORK ANYMORE
 socket.broadcast.to(socketid).emit('message', 'for your eyes only');// New way

Chciałem edytować post @soyuka, ale moja edycja została odrzucona przez recenzenta.


6

broadcast.emit wysyła wiadomość do wszystkich innych klientów (z wyjątkiem nadawcy)

socket.on('cursor', function(data) {
  socket.broadcast.emit('msg', data);
});

6

Emituj ściągę

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 individual socketid (private message)
  socket.to(<socketid>).emit('hey', 'I just met you');

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

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

};

4

Dla przestrzeni nazw w pokojach zapętlanie listy klientów w pokoju (podobnie do odpowiedzi Nav) jest jednym z dwóch podejść, które znalazłem, które będą działać. Drugim jest użycie wykluczenia. NA PRZYKŁAD

socket.on('message',function(data) {
    io.of( 'namespace' ).in( data.roomID ).except( socket.id ).emit('message',data);
}

7
z wyjątkiem został usunięty z 1.x: /
coulix

1

Inne przypadki

io.of('/chat').on('connection', function (socket) {
    //sending to all clients in 'room' and you
    io.of('/chat').in('room').emit('message', "data");
};

1

Zaktualizowano listę do dalszej dokumentacji.

socket.emit('message', "this is a test"); //sending to sender-client only
socket.broadcast.emit('message', "this is a test"); //sending to all clients except sender
socket.broadcast.to('game').emit('message', 'nice game'); //sending to all clients in 'game' room(channel) except sender
socket.to('game').emit('message', 'enjoy the game'); //sending to sender client, only if they are in 'game' room(channel)
socket.broadcast.to(socketid).emit('message', 'for your eyes only'); //sending to individual socketid
io.emit('message', "this is a test"); //sending to all clients, include sender
io.in('game').emit('message', 'cool game'); //sending to all clients in 'game' room(channel), include sender
io.of('myNamespace').emit('message', 'gg'); //sending to all clients in namespace 'myNamespace', include sender
socket.emit(); //send to all connected clients
socket.broadcast.emit(); //send to all connected clients except the one that sent the message
socket.on(); //event listener, can be called on client to execute on server
io.sockets.socket(); //for emiting to specific clients
io.sockets.emit(); //send to all connected clients (same as socket.emit)
io.sockets.on() ; //initial connection from a client.

Mam nadzieję że to pomoże.


„io.sockets.emit” jest taki sam jak „io.emit”, a nie „socket.emit”
Doctor.Who.

„socket.to („ gra ”). emituj„ równa się ”z„ socket.broadcast.to („gra”). emituj ”, więc powyższy komentarz jest błędny
Doctor.Who.

0

użyj tego kodowania

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

    socket.on('mousemove', function (data) {

        socket.broadcast.emit('moving', data);
    });

Ta funkcja socket.broadcast.emit () będzie emitować wszystko w funkcji oprócz serwera, który emituje


1
jak się do tego dostać, iojeśli wywołanie zwrotne jest zdefiniowane w
innym

Mam swoją aplikację w wielu plikach i łączę je z PrePros lub Koala zamiast ich wymagać, pozwala mi to udostępniać wszystkie ich zmienne
Steel Brain

1
Lub mając iojako globalny
Vadorequest

0

Korzystam z przestrzeni nazw i pokoi - znalazłem

socket.broadcast.to('room1').emit('event', 'hi');

do pracy gdzie

namespace.broadcast.to('room1').emit('event', 'hi');

nie

(czy ktokolwiek inny napotka ten problem)

Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.