Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a message to a particular client with socket.io

I'm starting with socket.io + node.js, I know how to send a message locally and to broadcast socket.broadcast.emit() function:- all the connected clients receive the same message.

Now, I would like to know how to send a private message to a particular client, I mean one socket for a private chat between 2 person (Client-To-Client stream). Thanks.

like image 408
Nizar B. Avatar asked Jul 04 '13 18:07

Nizar B.


People also ask

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.


2 Answers

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

Client Side:

var socket = io.connect('http://localhost'); socket.emit('join', {email: [email protected]}); 

Now, from the server side use that information to create an unique room for that user

Server Side:

var io = require('socket.io').listen(80);  io.sockets.on('connection', function (socket) {   socket.on('join', function (data) {     socket.join(data.email); // We are using room of socket io   }); }); 

So, now every user has joined a room named after user's email. So if you want to send a specific user a message you just have to

Server Side:

io.sockets.in('[email protected]').emit('new_msg', {msg: 'hello'}); 

The last thing left to do on the client side is listen to the "new_msg" event.

Client Side:

socket.on("new_msg", function(data) {     alert(data.msg); } 

I hope you get the idea.

like image 174
az7ar Avatar answered Sep 20 '22 05:09

az7ar


When a user connects, it should send a message to the server with a username which has to be unique, like an email.

A pair of username and socket should be stored in an object like this:

var users = {     '[email protected]': [socket object],     '[email protected]': [socket object],     '[email protected]': [socket object] } 

On the client, emit an object to the server with the following data:

{     to:[the other receiver's username as a string],     from:[the person who sent the message as string],     message:[the message to be sent as string] } 

On the server, listen for messages. When a message is received, emit the data to the receiver.

users[data.to].emit('receivedMessage', data) 

On the client, listen for emits from the server called 'receivedMessage', and by reading the data you can handle who it came from and the message that was sent.

like image 44
Adam Avatar answered Sep 18 '22 05:09

Adam