Javascript – How to send a message to a particular client with

I'm starting with + 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.

Best Solution

You can use 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:});

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

Server Side:

var io = require('').listen(80);

io.sockets.on('connection', function (socket) {
  socket.on('join', function (data) {
    socket.join(; // 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:'').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) {

I hope you get the idea.

Related Question