"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Exclude the Sender from Socket.IO Broadcasts?

How to Exclude the Sender from Socket.IO Broadcasts?

Published on 2024-11-09
Browse:231

How to Exclude the Sender from Socket.IO Broadcasts?

Sending Response to All Clients Except Sender

To broadcast a message to all connected clients, the io.sockets.emit() function is used. However, when you want to exclude the sender from receiving the broadcast, you may wonder about a more straightforward approach than checking the sender's ID on the client-side.

In Socket.IO, the socket.broadcast property provides a solution for this scenario. By using socket.broadcast.emit(), you can send a message to all clients except the sender. Here's an example:

socket.on('cursor', function(data) {
  socket.broadcast.emit('response', data);
});

In this example, when a client sends a 'cursor' event, the server broadcasts the received data to all other connected clients, excluding the sender.

Here's a summary of Socket.IO emit functions for your reference:

  • socket.emit(): Sends a message to the sender-client only.
  • io.emit(): Sends a message to all clients, including the sender.
  • socket.broadcast.emit(): Sends a message to all clients except the sender.
  • socket.broadcast.to(): Sends a message to all clients in a specific room or channel, except the sender.
  • socket.to(): Sends a message to the sender-client, only if they are in a specific room or channel.
  • io.in(): Sends a message to all clients in a specific room or channel, including the sender.
  • socket.broadcast.to(socketid): Sends a message to a specific client ID.
  • io.of(): Sends a message to all clients in a specific namespace, including the sender.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3