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]').
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With