javascriptnode.jssocket.iosocket.io-1.0

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?


Solution

  • There is a warning in API doc indicating why it does not work:

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

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