Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending message to specific client in Socket IO

People also ask

How do you send a message to a specific client with socket in python?

You can use socket.io rooms. From the client side emit an event ("join" in this case, can be anything) with any unique identifier (email, id). Server Side: io.sockets.in('[email protected]').

How do I send a socket message?

The send() function initiates transmission of a message from the specified socket to its peer. The send() function sends a message only when the socket is connected (including when the peer of the connectionless socket has been set via connect()). The length of the message to be sent is specified by the len argument.

Is socket.io good for chat?

So as we all know Socket.io is the best solution for instant messaging app and its reliability.


To send a message to a specific client you need to do it like so:

socket.broadcast.to(socketid).emit('message', 'for your eyes only');

Here is a nice little cheat sheet for sockets:

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

Credit to https://stackoverflow.com/a/10099325


The easiest way rather than sending directly to the socket, would be creating a room for the 2 users to use and just send messages freely in there.

socket.join('some-unique-room-name'); // Do this for both users you want to chat with each other
socket.broadcast.to('the-unique-room-name').emit('message', 'blah'); // Send a message to the chat room.

Otherwise, you're going to need to keep track of each individual clients socket connection, and when you want to chat you'll have to look up that sockets connection and emit specifically to that one using the function I said above. Rooms are probably easier.