Socket.io socket.broadcast.to not working

前端 未结 2 422
面向向阳花
面向向阳花 2021-01-15 10:27

I have in my Express server

userbase = {\'Fitz\': \'84Iw3MNEIMaed0GoAAAD\'}; //Exapmle user to receive message and associated socket id



//S         


        
相关标签:
2条回答
  • 2021-01-15 10:58

    Do you have users join a namespace on connection?

    socket.join(userbase[data_from_client.to_user]); //'84Iw3MNEIMaed0GoAAAD'
    

    You can try:

    socket.in(userbase[data_from_client.to_user]).emit('get_msg', {msg:data_server.msg});
    
    0 讨论(0)
  • 2021-01-15 11:10

    socket.broadcast().to() send a message to all users that match the to() arguments EXCEPT the user who's socket it is. So, socket.broadcast.to(socket.id) will never send to the actual socket user. In fact, by default, it won't send to anyone.

    Direct from the socket.io doc:

    To broadcast, simply add a broadcast flag to emit and send method calls. Broadcasting means sending a message to everyone else except for the socket that starts it.

    If you want to send to only a single socket, then just use:

    socket.emit(...)
    

    If you want to broadcast to a socket.id-type room and you want to include the user who's room it is, then use:

    io.to('some room').emit('some event'):
    

    So, you can change this:

    socket.broadcast.to(userbase[data_from_client.to_user]).emit('get_msg',{msg:data_server.msg});
    

    to this:

    io.to(userbase[data_from_client.to_user]).emit('get_msg',{msg:data_server.msg});
    
    0 讨论(0)
提交回复
热议问题