발신자를 제외한 모든 고객에게 응답 보내기


226

모든 고객에게 무언가를 보내려면 다음을 사용하십시오.

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

클라이언트로부터 수신하려면 다음을 사용하십시오.

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

클라이언트에서 서버로 메시지를 수신 할 때 메시지를 보내는 사람을 제외한 모든 사용자에게 해당 메시지를 보내도록이 둘을 어떻게 결합 할 수 있습니까?

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

메시지와 함께 클라이언트 ID를 보낸 다음 클라이언트 쪽을 확인하여 해킹해야합니까? 아니면 더 쉬운 방법이 있습니까?

답변:


840

다음은 내 목록입니다 (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
이것을 FAQ 에 공헌 하시겠습니까 ? 아니면 내가 당신을 위해 그것을 할 수 있습니까? (여기서 뒤로 링크를 제공합니다)
Kos

1
나는 여기에 io없습니다.socket
chovy

2
// sending to all clients except sender무엇을 보완해야 // sending a response to sender client only 합니까?
Basj

4
당신은에 따른 추가 시겠어요 의 소켓 번호 , socket.to('others').emit('an event', { some: 'data' });또한 방송 방에.
gongzhitaao

119
이것은 socket.io 문서의 모든 것보다 더 유용합니다
Jonathan.

43

@LearnRPG 답변에서 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');

@Crashalot 의견에 대한 답변 socketid은 다음과 같습니다.

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

3
대박! socketid개별 소켓으로 보내 려면 어떻게해야 합니까?
Crashalot

2
질문에 대한 답변으로 수정되었습니다. 기본적으로 socket.id소켓 객체에서 온 것입니다.
soyuka

당신이 @Crashalot 그것을하거나 그룹화 할 수 있습니다 conncected 클라이언트를 전송 socket.emit 다시 사용 할 수있는 개인에게 보내는
ujwal dhakal

12

다음은 0.9.x에서 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

@soyuka의 게시물을 편집하고 싶었지만 피어 리뷰에서 편집을 거부했습니다.


6

broadcast.emit는 msg를 다른 모든 클라이언트에게 보냅니다 (발신인 제외)

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

6

치트 시트 방출

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

룸 내 네임 스페이스의 경우 룸 내 클라이언트 목록 (Nav의 답변과 유사)은 내가 찾은 두 가지 접근법 중 하나입니다. 다른 하나는 제외를 사용하는 것입니다. EG

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

7
를 제외하고 1.x에서 제거되었습니다 : /
coulix

1

다른 경우

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

1

추가 문서를 위해 목록을 업데이트했습니다.

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.

도움이 되었기를 바랍니다.


'io.sockets.emit'은 'socket.emit'이 아닌 'io.emit'과
동일합니다.

'socket.to ('game '). emit'은 'socket.broadcast.to ('game '). emit'과 같으므로 위의 주석이 잘못되었습니다
Doctor.Who.

0

이 코딩을 사용하십시오

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

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

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

이 socket.broadcast.emit ()은 방출중인 서버를 제외하고 함수에서 모든 것을 방출합니다.


1
io콜백이 다른 파일에 정의되어있는 경우 어떻게해야합니까
chovy

여러 파일로 된 앱을 보유하고 있으며, 필요하지 않고 PrePros 또는 Koala와 연결하면 모든 변수를 공유 할 수 있습니다.
Steel Brain

1
또는 io세계적으로
Vadorequest

0

네임 스페이스와 룸을 사용하고 있습니다.

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

어디서 일하러

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

하지 않았다

(다른 사람이 그 문제에 직면해야합니까)

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.