Send message to specific client with socket.io and node.js Send message to specific client with socket.io and node.js javascript javascript

Send message to specific client with socket.io and node.js


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

In short you must now save the socket.id 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("socket.io");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", socket.id, function(err) {      if (err) throw err;      console.log("Master socket is now" + socket.id);    });  });  socket.on("message to master", function(msg) {    // Fetch the socket id from Redis    client.get("mastersocket", function(err, socketId) {      if (err) throw err;      io.sockets.socket(socketId).emit(msg);    });  });});

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 http://nodejs.org/api/cluster.html


each socket joins a room with a socket id for a name, so you can just

io.to(socket#id).emit('hey')

docs: http://socket.io/docs/rooms-and-namespaces/#default-room

Cheers


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

var io = io.listen(server);io.clients[sessionID].send()

Which may break, I 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.