Gửi phản hồi cho tất cả khách hàng ngoại trừ người gửi


226

Để gửi một cái gì đó cho tất cả khách hàng, bạn sử dụng:

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

Để nhận từ khách hàng, bạn sử dụng:

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

Làm cách nào tôi có thể kết hợp cả hai để khi nhận được tin nhắn trên máy chủ từ máy khách, tôi gửi tin nhắn đó cho tất cả người dùng ngoại trừ người gửi tin nhắn?

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

Tôi có phải hack nó bằng cách gửi id khách hàng với tin nhắn và sau đó kiểm tra phía máy khách hay có cách nào dễ dàng hơn không?

Câu trả lời:


840

Đây là danh sách của tôi (cập nhật cho 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
Bạn có muốn đóng góp điều này cho FAQ ? hoặc tôi có thể làm điều đó cho bạn? (Tôi sẽ cung cấp một backlink ở đây)
Kos

1
tôi không' có một iohere.onlysocket
chovy

2
Để bổ sung // sending to all clients except sender, sử dụng để làm // sending a response to sender client only gì?
Basj

4
Bạn có thể vui lòng thêm rằng theo socket # in , socket.to('others').emit('an event', { some: 'data' });cũng phát sóng trong một phòng.
gongzhitaao

119
Điều này hữu ích hơn tất cả mọi thứ trên tài liệu socket.io kết hợp
Jonathan.

43

Từ câu trả lời @LearnRPG nhưng với 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');

Để trả lời bình luận @Crashalot, socketidxuất phát từ:

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

3
Tuyệt vời! Làm thế nào để bạn nhận được socketidđể gửi đến một ổ cắm cá nhân?
Crashalot

2
Chỉnh sửa với một câu trả lời cho câu hỏi của bạn. Về cơ bản nó là socket.idtừ đối tượng ổ cắm của bạn.
Soyuka

để gửi cho cá nhân, bạn có thể sử dụng socket.emit trở lại người gửi nó hoặc bạn có thể nhóm các khách hàng được kết nối và thực hiện @Crashalot
ujwal dhakal

12

Dưới đây là câu trả lời đầy đủ hơn về những gì đã thay đổi từ 0.9.x thành 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

Tôi muốn chỉnh sửa bài đăng của @soyuka nhưng bản chỉnh sửa của tôi đã bị từ chối bởi đánh giá ngang hàng.


6

Broadcast.emit gửi tin nhắn cho tất cả các khách hàng khác (ngoại trừ người gửi)

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

6

Phát ra áo

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

Đối với các không gian tên trong các phòng lặp lại danh sách khách hàng trong một phòng (tương tự như câu trả lời của Nav) là một trong hai cách tiếp cận tôi thấy sẽ hiệu quả. Khác là sử dụng loại trừ. VÍ DỤ

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

7
ngoại trừ đã bị xóa khỏi 1.x: /
coulix

1

Các trường hợp khác

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

1

Cập nhật danh sách cho các tài liệu thêm.

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.

Hi vọng điêu nay co ich.


'io.sockets.emit' giống như 'io.emit', không phải 'socket.emit'
Doctor.Who.

'socket.to (' game '). emit' bằng 'socket.broadcast.to (' game '). emit' nên nhận xét trên là sai
Doctor.Who.

0

sử dụng mã hóa này

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

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

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

socket.broadcast.emit () này sẽ phát ra mọi thứ trong hàm ngoại trừ máy chủ đang phát ra


1
Làm thế nào để bạn nhận được iobên trong này nếu cuộc gọi lại được xác định trong tệp bao phấn
chovy

Tôi có ứng dụng của mình trong nhiều tệp và tôi kết hợp chúng với PrePros hoặc Koala thay vì yêu cầu chúng, nó cho phép tôi chia sẻ tất cả các biến của chúng
Steel Brain

1
Hoặc có iotoàn cầu
Vadorequest

0

Tôi đang sử dụng không gian tên và phòng - Tôi tìm thấy

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

đi làm ở đâu

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

đã không

(nếu ai khác phải đối mặt với vấn đề đó)

Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.