Reputation: 1037
socket.on('private-message', function(data){
console.log("Sending: " + data.content + " to " + data.username);
console.log(clients[data.username].socket.join(', '));
if (clients[data.username]){
io.sockets.connected[clients[data.username].socket].emit("add-message", data);
} else {
console.log("User does not exist: " + data.username);
}
});
This code is working fine but what I want is, I want to send multiple connected clients connected to the socket using their socket id.
io.sockets.connected[reciver.socketid].emit("add-message", data);
Is there any way or is it is possible to write the group of receiver socket.id. I don't want to use for loop.
Upvotes: 2
Views: 9384
Reputation: 5542
Feel free to use my Socket.IO Cheatsheet!
// Add socket to room
socket.join('some room');
// Remove socket from room
socket.leave('some room');
// Send to current client
socket.emit('message', 'this is a test');
// Send to all clients include sender
io.sockets.emit('message', 'this is a test');
// Send to all clients except sender
socket.broadcast.emit('message', 'this is a test');
// Send to all clients in 'game' room(channel) except sender
socket.broadcast.to('game').emit('message', 'this is a test');
// Send to all clients in 'game' room(channel) include sender
io.sockets.in('game').emit('message', 'this is a test');
// Send to individual socket id
io.sockets.socket(socketId).emit('message', 'this is a test');
Here's the official cheatsheet for Socket.IO.
Upvotes: 10
Reputation: 321
Ah! I didn't read the docs correct! thanks all!: )
I was looking for this... io.sockets.emit('Test1', response); I was using this... socket.emit("Test1", response);
:)
Upvotes: 0
Reputation:
You can make subscribe to all user to a room and then you can emit message.
socket.join('some room');
Upvotes: 0
Reputation: 1037
Yes its solved now!! Here we go with answer.
io.to(socketid1).to(socketid2).emit("add-message", data);
Or you can do this by joining clients to a group. And emit message to that group.
join
socket.join(data.username);
emit
socket.join(data.username);
This saved me from writing lot of codes
Upvotes: 9