2
votes
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.

4
socket.broadcast.emit('broadcast', 'hello friends!'); - Dipak
in that broadcast is your "add-message" - Dipak
let me know if you have an issue. - Dipak
I don't want to just broadcast all. I want to emit only particular or selected clients using their socket.id. Not all.. - Biswajit
then you should loop through or create an specific intended client's array and send the message my friend. - Dipak

4 Answers

9
votes

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');

Update 2021

Here's the official cheatsheet for Socket.IO.

7
votes

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

0
votes

You can make subscribe to all user to a room and then you can emit message.

socket.join('some room');
0
votes

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);

:)