【问题标题】:socket.to(roomId).emit not working after reconnectsocket.to(roomId).emit 重新连接后不起作用
【发布时间】:2018-04-26 13:24:59
【问题描述】:

我想解释一下我最近几天一直面临的一个问题,但我无法解决。我正在使用 socket.io,使用房间向多个客户端发射。我正在测试重新连接的情况(例如,由于 wi-fi 连接失败)。

情况如下: 客户端:

socket.on('reconnect', function () {
    var socketId = socket.id;
    socket.emit('reconnectAttempt',{
        id: $matchId,
        username: $username,
        socketId: socketId
    });
    log("you were reconnected");
});

服务器端:

socket.on('reconnectAttempt',function(data){
    listClientsInRoom(data.id);
    socket.join(data.id); // Since socket.id changes after reconnect
    listClientsInRoom(data.id);
    socket.to(data.id).emit('reconnect attempt succeeded');
};

地点:

function listClientsInRoom(key){
    var clients = io.sockets.adapter.rooms[key].sockets;
    console.log('___Clients in room:'+JSON.stringify(clients));
}

输出类似于(在这种情况下,只有一个客户端重新连接):

___Clients in room:{"mfA-h4IkTtUMgPNsAAAD":true}
___Clients in room:{"mfA-
h4IkTtUMgPNsAAAD":true,"ShdVRVzVr4x4WCggAAAE":true}

在这种情况下,重新连接事件后的 socket.id 是 ShdVRVzVr4x4WCggAAAE。 然后,有了这种情况,似乎套接字已正确添加 到房间,但正如你所见,加入后,我会这样做:

socket.to(data.id).emit('reconnect attempt succeeded');

这应该只在客户端(在所有房间)中进行日志记录,并且适用于除重新连接的客户端之外的所有客户端。如果我这样做:

socket.emit('reconnect attempt succeeded');

相反,我会正确地看到日志。

有人可以帮帮我吗?

谢谢

【问题讨论】:

    标签: node.js sockets websocket socket.io


    【解决方案1】:

    愚蠢的错误,只是尝试使用此“重新连接尝试成功”事件,从问题中可以看出,调用错误。

    问题:

    socket.to(data.id).emit('reconnect attempt succeeded');
    

    正确的方法

    io.to(data.id).emit('reconnect attempt succeeded');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-18
      • 2016-08-08
      • 2018-12-11
      • 1970-01-01
      • 1970-01-01
      • 2019-01-03
      • 2018-12-13
      相关资源
      最近更新 更多