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.
Appreciated!
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);
This should do it
servio.sockets.socket(id).emit('hello');
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.
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;
players.push(player);
});
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){
players.splice(i,1);
break;
}
}
});
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);
break;
}
}
});
Hope that helps somewhat.
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.
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})
This should work:
servio.sockets.sockets[playId].emit(...)
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...
(^CoffeeScript^)