Отправлять ответ всем клиентам, кроме отправителя
Чтобы отправить что-то всем клиентам, вы используете:
io.sockets.emit('response', data);
Чтобы получать от клиентов, вы используете:
socket.on('cursor', function(data) {
...
});
Как я могу объединить эти два, чтобы при получении сообщения на сервере от клиента я отправлял это сообщение всем пользователям, кроме тех, кто отправил сообщение?
socket.on('cursor', function(data) {
io.sockets.emit('response', data);
});
Должен ли я его взломать, отправив идентификатор клиента с сообщением, а затем проверить на стороне клиента или есть более простой способ?
Ответы
Ответ 1
Вот мой список (обновленный для 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');
Ответ 2
Из ответа @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
Вот более полный ответ о том, что изменилось с 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, но мое редактирование было отклонено экспертным обзором.
Ответ 4
broadcast.emit отправляет msg всем другим клиентам (кроме отправителя)
socket.on('cursor', function(data) {
socket.broadcast.emit('msg', data);
});
Ответ 5
Для пространств имен в комнатах, зацикливающих список клиентов в комнате (аналогично Nav ответе), один из двух подходов, которые я нашел, будет работать. Другой - использовать исключение. Например.
socket.on('message',function(data) {
io.of( 'namespace' ).in( data.roomID ).except( socket.id ).emit('message',data);
}
Ответ 6
Другие случаи
io.of('/chat').on('connection', function (socket) {
//sending to all clients in 'room' and you
io.of('/chat').in('room').emit('message', "data");
};
Ответ 7
Обновлен список для дальнейшей документации.
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.
Надеюсь, что это поможет.
Ответ 8
используйте это кодирование
io.sockets.on('connection', function (socket) {
socket.on('mousemove', function (data) {
socket.broadcast.emit('moving', data);
});
этот файл socket.broadcast.emit() будет генерировать все в функции, кроме сервера, который испускает
Ответ 9
Я использую пространства имен и комнаты - я нашел
socket.broadcast.to('room1').emit('event', 'hi');
чтобы работать там, где
namespace.broadcast.to('room1').emit('event', 'hi');
не
(если кто-то еще столкнется с этой проблемой)