Send message to specific client with and node.js


I'm working with and node.js and until now it seems pretty good, but I don't know how to send a message from the server to an specific client, something like this:

client.send(message, receiverSessionId)

But neither the .send() nor the .broadcast() methods seem to supply my need.

What I have found as a possible solution, is that the .broadcast() method accepts as a second parameter an array of SessionIds to which not send the message, so I could pass an array with all the SessionIds connected at that moment to the server, except the one I wish send the message, but I feel there must be a better solution.

Any ideas?

10/1/2017 3:36:51 PM

Accepted Answer

Well you have to grab the client for that (surprise), you can either go the simple way:

var io = io.listen(server);

Which may break, I hardly doubt it, but it's always a possibility that io.clients might get changed, so use the above with caution

Or you keep track of the clients yourself, therefore you add them to your own clients object in the connection listener and remove them in the disconnect listener.

I would use the latter one, since depending on your application you might want to have more state on the clients anyway, so something like clients[id] = {conn: clientConnect, data: {...}} might do the job.

3/13/2019 1:27:25 AM

Ivo Wetzel's answer doesn't seem to be valid in 0.9 anymore.

In short you must now save the and use io.sockets.socket(savedSocketId).emit(...) to send messages to it.

This is how I got this working in clustered Node.js server:

First you need to set Redis store as the store so that messages can go cross processes:

var express = require("express");
var redis = require("redis");
var sio = require("");

var client = redis.createClient()
var app = express.createServer();
var io = sio.listen(app);

io.set("store", new sio.RedisStore);

// In this example we have one master client socket 
// that receives messages from others.

io.sockets.on('connection', function(socket) {

  // Promote this socket as master
  socket.on("I'm the master", function() {

    // Save the socket id to Redis so that all processes can access it.
    client.set("mastersocket",, function(err) {
      if (err) throw err;
      console.log("Master socket is now" +;

  socket.on("message to master", function(msg) {

    // Fetch the socket id from Redis
    client.get("mastersocket", function(err, socketId) {
      if (err) throw err;


I omitted the clustering code here, because it makes this more cluttered, but it's trivial to add. Just add everything to the worker code. More docs here

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow