Emit to Socket IO socket.id

2019-04-10 05:44发布

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);

6条回答
Evening l夕情丶
2楼-- · 2019-04-10 05:52

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.

查看更多
淡お忘
3楼-- · 2019-04-10 05:55

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.

查看更多
Fickle 薄情
4楼-- · 2019-04-10 05:55

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^)

查看更多
▲ chillily
5楼-- · 2019-04-10 05:59

This should work:

servio.sockets.sockets[playId].emit(...)
查看更多
别忘想泡老子
6楼-- · 2019-04-10 06:05

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.

查看更多
beautiful°
7楼-- · 2019-04-10 06:09

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})
查看更多
登录 后发表回答