Socket.io 客户端未收到事件

Socket.io client not receiving events

当两个客户加入聊天室时,我想向他们每个人发送一条独特的消息。第一个客户端收到消息,但第二个客户端没有。这是代码:

io.on('connection', (socket) => {
var roomName
var firstPlayer
var secondPlayer
var connectedClients

socket.on('roomName', (obj) => {
    roomName = obj.name
    socket.join(roomName)
    connectedClients = Object.keys(io.sockets.adapter.rooms[roomName].sockets)

    if( connectedClients.length > 1 ){
        firstPlayer = connectedClients[0]
        secondPlayer = connectedClients[1]
        // sending the icon decision
        socket.to(firstPlayer).emit( 'iconDecide', { iAmX: true } )
        socket.to(secondPlayer).emit( 'iconDecide', { iAmX: false } )
    }
})

socket.on('move', (obj) => {
    socket.to(roomName).emit('receiveMove', obj)
}) })

我该如何调试它?如果 socket.io 无法发送消息,我有什么方法可以看到错误吗?

API doc 中有一个警告说明它为什么不起作用:

// sending to individual socketid (private message)
io.to(`${socketId}`).emit('hey', 'I just met you');
// WARNING: `socket.to(socket.id).emit()` will NOT work, as it will send to 
everyone in the room
// named `socket.id` but the sender. Please use the classic `socket.emit()` 
instead.

您可以使用 socket.broadcast,如 API doc 中所述:

socket.broadcast.to(socketId).emit('msg', 'msg data');