socket.broadcast.to().emit() vs socket.to().emit()

回眸只為那壹抹淺笑 提交于 2021-01-29 19:59:59

问题


What is the difference between:

socket.broadcast.to().emit()

and

socket.to().emit()

Here on the socket.io cheat sheet it says

  socket.to('game').emit('nice game', "let's play a game"); // sending to all clients in 'game' room except sender

Then in this tutorial blog it says:

socket.broadcast.to('game').emit('message', 'nice game'); //sending to all clients in 'game' room(channel) except sender
socket.to('game').emit('message', 'enjoy the game'); //sending to sender client, only if they are in 'game' room(channel)

So now I am really confused.

  1. Is one of this explanations wrong?

  2. What does sending to sender client, only if they are in 'game' room(channel) mean? Does it mean if it is a group chat only one person(the sender of the message) will receive it? What does it mean?

  3. If the socket.io cheatsheet is accurate, what is the purpose of .broadcast.emit() if sending to all clients in 'game' room except sender is done by calling: socket.to('game').emit();? Is socket.broadcast.emit() only used to send to all clients on the same namespace(except the sender)? But if you want to send to all clients in a particular room (except the sender) you use socket.to().emit() instead of socket.broadcast.to().emit()?

Thank you.


回答1:


On "https://dev.to/moz5691/socketio-for-simple-chatting---1k8n

socket.to('game').emit('message', 'enjoy the game'); //sending to sender client, only if they are in 'game' room(channel)".

This particular emit is from server to the sender client only in the game room channel.

However the broadcast, socket.broadcast.to('game').emit('message', 'nice game'); Sends to all clients in 'game' room(channel) except sender.

Noticed there is one more error in the following paragraph where he explains:

Client --> sendMesssage --> Server

Server <-- receiveMessage -- Server

It should be Client <-- receiveMessage -- Server.

Hope that helps.



来源:https://stackoverflow.com/questions/57458399/socket-broadcast-to-emit-vs-socket-to-emit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!