问题
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.
Is one of this explanations wrong?
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?
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();
? Issocket.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 usesocket.to().emit()
instead ofsocket.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