javascriptnode.jswebsocketsocket.ioserver-side

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


I'm working with socket.io 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?


Solution

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