Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending message to a unique socket

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.

like image 596
John Watson Avatar asked Oct 31 '11 13:10

John Watson


1 Answers

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.

like image 63
geoffreak Avatar answered Nov 12 '22 03:11

geoffreak