Skip to main content
WebSockets Tutorial
CHAPTER 09 Beginner

Broadcasting Messages to Multiple Clients

Updated: May 14, 2026
20 min read

# CHAPTER 9

Broadcasting Messages to Multiple Clients

1. Introduction

A chat application is useless if you are only talking to yourself. The true power of a WebSocket server lies in its ability to manage multiple active connections simultaneously. When one user sends a message, the server acts as a dispatcher, pushing that message out to everyone else. This action is known as Broadcasting. In this chapter, we will explore the theory and architecture behind broadcasting to multiple clients.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define "Broadcasting" in the context of WebSockets.
  • Understand how a server maintains a list of connected clients.
  • Explain the concept of "Rooms" or "Channels".
  • Trace the flow of a message from one sender to multiple receivers.

3. Beginner-Friendly Explanation

Imagine a teacher in a classroom full of students.
  • Point-to-Point (Echo): A student hands the teacher a note. The teacher reads it and hands it right back to that specific student. Nobody else sees it.
  • Broadcasting: A student hands the teacher a note. The teacher stands up and reads the note loudly so the entire classroom can hear it.

In WebSockets, every time a user connects, the server adds them to a "classroom" (an array or list of connections). When a message arrives, the server loops through that list and sends the message to everyone.

4. Real-World Examples

  • Global Broadcast: A server-wide notification in an online game ("Server will restart in 5 minutes"). It goes to every single connected user.
  • Room Broadcast: A WhatsApp group chat. Only the 10 people inside the "Family Group" room receive the broadcast, not the millions of other users on WhatsApp.

5. Architectural Step-by-Step

Let's look at the logical steps a server must take to execute a broadcast. We will look at PHP code in a later chapter, but here is the universal logic.

Step 1: Server starts up and creates an empty list called Clients = []. Step 2: User A connects. Server adds User A to the list: Clients = [A]. Step 3: User B connects. Server adds User B: Clients = [A, B]. Step 4: User A sends a message to the server: "Hello everyone!". Step 5: Server receives the message, runs a foreach loop over Clients, and calls send("Hello everyone!") on both A and B.

6. The "Echo vs Broadcast" Problem

If the server sends the message back to *everyone*, User A will receive their own message back. Usually, the sender has already displayed their own message on their screen (Optimistic UI, from Chapter 8). If the server broadcasts to everyone indiscriminately, User A will see their message appear twice! The solution is to broadcast to everyone *except* the sender.

7. Conceptual Server Logic (Pseudocode)

Here is how broadcasting logic looks in almost every programming language:
text
1234567891011
function onMessage(senderConnection, incomingMessage) {
    
    // Loop through every person currently connected
    foreach (client in globalClientsList) {
        
        // Don't send it back to the person who wrote it!
        if (client !== senderConnection) {
            client.send(incomingMessage);
        }
    }
}

8. JSON Structure for Rooms

To implement "Rooms", the client needs to tell the server *where* to broadcast the message. We use JSON for this.
json
12345
{
  "action": "send_to_room",
  "room": "gaming_lounge",
  "message": "Who wants to play?"
}

The server then checks its memory, finds the gaming_lounge array, and only loops through those specific clients.

9. PHP Broadcasting Preview (Ratchet)

When we build our PHP server later, the code for broadcasting will look remarkably similar to our pseudocode:
php
123456789
<?php
public function onMessage(ConnectionInterface $from, $msg) {
    foreach ($this->clients as $client) {
        if ($from !== $client) {
            // The sender is not the receiver, send to each client connected
            $client->send($msg);
        }
    }
}

10. Best Practices

  • Manage Disconnections: If User B loses internet, the server must remove User B from the Clients array immediately. If it tries to broadcast to a dead connection, it will throw an error and potentially crash the loop.
  • Use JSON for routing: Never try to parse plain strings on the server to determine who gets a message. Always wrap messages in JSON objects with an explicit type or action property.

11. Common Mistakes

  • Forgetting to exclude the sender: Resulting in duplicate messages showing up on the sender's screen.
  • Blocking the Event Loop: If a server has 10,000 clients, a single broadcast requires looping 10,000 times. If the broadcast logic takes too long, it will freeze the server. Efficient memory management is key.

12. Mini Exercises

  1. 1. Sketch a diagram on a piece of paper: Draw one Server in the middle, and 3 Clients (A, B, C) connected to it. Draw an arrow from A to Server labeled "Message". Then draw arrows from Server to B and Server to C. You have just mapped out a Broadcast!

13. Coding Challenges

Challenge 1: Write a JSON object payload that a client might send if they want to join a specific chat room called "tech-support", rather than sending a message.

14. MCQs with Answers

Question 1

What is the primary purpose of broadcasting in a WebSocket server?

Question 2

Why do servers usually exclude the sender during a broadcast?

15. Interview Questions

  • Q: How does a WebSocket server keep track of who is currently online?
  • Q: Explain how you would architect a "Private Message" feature (Client A to Client B) instead of a global broadcast.

16. FAQs

Q: Does broadcasting use a lot of server CPU? A: Yes, broadcasting a message to thousands of users requires high concurrency. This is why languages/environments that excel at async event loops (Node.js, Go, or PHP with Swoole/ReactPHP) are favored for massive WebSocket servers.

17. Summary

In Chapter 9, we moved beyond point-to-point connections to understand Broadcasting. By maintaining an array of active connections, a WebSocket server can act as a central hub, receiving a single message and instantly dispersing it to everyone else. This core concept is the foundation of every multiplayer game and chat room on the internet.

18. Next Chapter Recommendation

While broadcasting is powerful, what happens when a user's mobile internet flickers and they disconnect? Proceed to Chapter 10: Handling Connection States and Errors, where we will engineer an auto-reconnecting client to ensure seamless user experiences.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·