简体   繁体   English

Socket.io客户端未收到事件

[英]Socket.io client not receiving events

When two clients join a chatroom, I want to send each of them a unique message. 当两个客户加入聊天室时,我想向他们发送一条唯一的消息。 The first client is getting the message, but the second client is not. 第一个客户端收到消息,但第二个客户端没有收到消息。 This is the code: 这是代码:

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

How do I debug this? 我该如何调试? Is there any way I can see an error if socket.io is not able to send the message? 如果socket.io无法发送消息,有什么办法可以看到错误?

There is a warning in API doc indicating why it does not work: API文档中有一个警告,指出为什么它不起作用:

// 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.

You can use socket.broadcast as mentioned in API doc : 您可以使用API doc中提到的socket.broadcast

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM