Home > Web Front-end > JS Tutorial > body text

How to Exclude the Sender from Socket.IO Broadcasts?

Barbara Streisand
Release: 2024-10-31 02:02:29
Original
232 people have browsed it

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:

<code class="javascript">socket.on('cursor', function(data) {
  socket.broadcast.emit('response', data);
});</code>
Copy after login

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.

The above is the detailed content of How to Exclude the Sender from Socket.IO Broadcasts?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!