To send something to all clients, you use:
JavaScript
x
2
1
io.sockets.emit('response', data);
2
To receive from clients, you use:
JavaScript
1
4
1
socket.on('cursor', function(data) {
2
3
});
4
How can I combine the two so that when recieving a message on the server from a client, I send that message to all users except the one sending the message?
JavaScript
1
4
1
socket.on('cursor', function(data) {
2
io.sockets.emit('response', data);
3
});
4
Do I have to hack it around by sending the client-id with the message and then checking on the client-side or is there an easier way?
Advertisement
Answer
Here is my list (updated for 1.0):
JavaScript
1
29
29
1
// sending to sender-client only
2
socket.emit('message', "this is a test");
3
4
// sending to all clients, include sender
5
io.emit('message', "this is a test");
6
7
// sending to all clients except sender
8
socket.broadcast.emit('message', "this is a test");
9
10
// sending to all clients in 'game' room(channel) except sender
11
socket.broadcast.to('game').emit('message', 'nice game');
12
13
// sending to all clients in 'game' room(channel), include sender
14
io.in('game').emit('message', 'cool game');
15
16
// sending to sender client, only if they are in 'game' room(channel)
17
socket.to('game').emit('message', 'enjoy the game');
18
19
// sending to all clients in namespace 'myNamespace', include sender
20
io.of('myNamespace').emit('message', 'gg');
21
22
// sending to individual socketid
23
socket.broadcast.to(socketid).emit('message', 'for your eyes only');
24
25
// list socketid
26
for (var socketid in io.sockets.sockets) {}
27
OR
28
Object.keys(io.sockets.sockets).forEach((socketid) => {});
29