Sending message to a unique socket

John Watson picture John Watson · Oct 31, 2011 · Viewed 8.5k times · Source

I am using node.js and socket.io to create a chat application. How to send message to another socket, I know the id of the socket or the username only. There are no rooms , clients chat one on one.

Answer

geoffreak picture geoffreak · Oct 31, 2011

With Socket.IO, you aren't restricted to only using the socket object within the callback of the connection function. You can create an object that stores the socket object for a particular username and look up the socket to send a message to when a client emits a message. You would need to transmit the intended target with every message.

Example:

var sockets = {};

...

io.on('connection', function(socket){
    socket.on('set nickname', function (name) {
        sockets[name] = socket;
    });
    socket.on('send message', function (message, to) {
        sockets[to].emit(message);
    });
});

See more examples on the examples page of Socket.IO's website.