Emit to Socket IO socket.id


I am trying to emit to a particular socket ID:

socket(user[playID]).emit('correct', data);

But I'm getting:

TypeError: object is not a function

if I log out user[playID] I do get a valid socket ID.


Here is my setup in case I'm missing something:.

// Tell Socket.io to pay attention
servio  = io.listen(server);

// Tell HTTP Server to begin listening for connections on port 3250
sock    = server.listen(3250);
Problem courtesy of: Matthew Starkey


This should do it


This answer covers the same/similar topic. In short, consider keeping a reference to the connected clients yourself and emit to them as desired, rather than relying on socket.io's internals, which could change.

Solution courtesy of: Jaz Lalli


Per http://socket.io/docs/rooms-and-namespaces/,

Each Socket in Socket.IO is identified by a random, unguessable, unique identifier Socket#id. For your convenience, each socket automatically joins a room identified by this id.

You emit to a room like:

io.to('some room').emit('some event')

If you want to emit to just a specific socket.id, just replace 'some room' with the associated id.

Discussion courtesy of: user2755758

This should work:

Discussion courtesy of: robertklep

UPDATE: in socket.io-1.4 you have to prepend "/#" to socket id ( very frustrating that it doesnt work now). you can also view all connected sockets from backend as io.sockets.connected

io.to( "/#" + socket_id).emit("event_name",{data:true})
Discussion courtesy of: Alex G

Another way to do this is:

var players = [];

io.sockets.on('connection', function(socket){

    socket.on('skt_init', function (data) {
            var player = new Object();
            player.id = data.id;
            player.socket = socket.id;

    socket.on('disconnect', function() {        
        var len = 0;

        for(var i=0, len=players.length; i<len; ++i ) {
            var p = players[i];

            if(p.socket == socket.id){

    socket.on('skt_event', function(data, id_player){
        var len = 0;

        for(var i=0, len=players.length; i<len; ++i ) {
            var p = players[i];
            if(p.id == id_player){
                io.sockets.socket(p.socket).emit('correct', data);

Hope that helps somewhat.

Discussion courtesy of: alditis

Since socket.io doesn't provide a stable API to get the socket from a socket's ID, you can simply (and easily) keep track of them with an object keyed by socket IDs.

sockets_by_id = {}

io.on "connection", (socket)->
    sockets_by_id[socket.id] = socket

sockets_by_id[socket_id].emit event, data...


Discussion courtesy of: 1j01

This recipe can be found in it's original form on Stack Over Flow.