Rodolfo Palma Rodolfo Palma - 10 months ago 76
Node.js Question

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
nor the
methods seem to supply my need.

What I have found as a possible solution, is that the
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?


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 for the clients anyway, so something like clients[id] = {conn: clientConnect, data: {...}} might do the job.