Home >Web Front-end >JS Tutorial >How to Exclude the Sender from Receiving a Response in Socket.IO?
How to Send Response to All Clients Except the Sender in Socket.IO?
Socket.IO offers a range of methods for communication between clients and the server. To send messages to all clients, you can use io.sockets.emit('response', data);. However, when you need to exclude the sending client from receiving the response, this approach falls short.
A Simple Solution: socket.broadcast.emit()
The solution lies in using the socket.broadcast.emit() method. This method sends a message to all connected clients except the one that sent it. The usage is straightforward:
<code class="javascript">socket.on('cursor', function(data) { socket.broadcast.emit('response', data); });</code>
In this example, when a client emits a 'cursor' event, the server sends the data back to all other clients using socket.broadcast.emit().
Additional Broadcasting Options
Socket.IO also provides additional broadcasting options that allow for more granular control:
By understanding these broadcasting methods, you can efficiently manage communication between clients and the server, ensuring that messages reach the intended recipients only.
The above is the detailed content of How to Exclude the Sender from Receiving a Response in Socket.IO?. For more information, please follow other related articles on the PHP Chinese website!