Multiple Clients - potatoscript/websocket GitHub Wiki

🀝 Handle Multiple Clients in WebSockets

πŸ’‘ Imagine building a chatroom, a multiplayer game, or a collaborative document editorβ€”all of these require managing multiple WebSocket clients efficiently.


πŸ—οΈ How Does WebSocket Handle Multiple Clients?

πŸ”— Each client connects to the same WebSocket server

  • The server tracks all connected clients.
  • When a client sends a message, the server decides whether to:
    1️⃣ Reply to the sender βœ‰οΈ
    2️⃣ Broadcast to all clients πŸ“’
    3️⃣ Send a message to a specific client 🎯

πŸ“Œ Step 1: Setting Up a WebSocket Server for Multiple Clients

πŸ“‚ Create a new file called multi-server.js

const WebSocket = require('ws');

// Create WebSocket server on port 8080
const wss = new WebSocket.Server({ port: 8080 });

console.log("βœ… WebSocket Server running on ws://localhost:8080");

// Store all connected clients
const clients = new Set();

// Handle client connections
wss.on('connection', (ws) => {
    console.log("πŸ”— New client connected!");
    clients.add(ws);

    // Notify everyone that a new client has joined
    broadcastMessage("πŸ“’ A new client has joined the chat!");

    // Handle incoming messages
    ws.on('message', (message) => {
        console.log(`πŸ“© Received: ${message}`);
        broadcastMessage(`πŸ‘€ Client: ${message}`);
    });

    // Handle client disconnection
    ws.on('close', () => {
        console.log("❌ Client disconnected.");
        clients.delete(ws);
        broadcastMessage("❌ A client has left the chat.");
    });
});

// Function to broadcast messages to all clients
function broadcastMessage(message) {
    clients.forEach(client => {
        if (client.readyState === WebSocket.OPEN) {
            client.send(message);
        }
    });
}

πŸ”Ή How this works:

  • clients.add(ws) stores each client in a Set.
  • ws.on('message', …) listens for messages from clients.
  • broadcastMessage() sends messages to all connected clients.

πŸ“Œ Step 2: Creating a WebSocket Client for Multiple Users

πŸ“‚ Create a new file called multi-client.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Multi-Client WebSocket</title>
    <style>
        body { font-family: Arial, sans-serif; text-align: center; }
        input { padding: 10px; margin: 10px; width: 80%; }
        button { padding: 10px; cursor: pointer; }
        ul { list-style-type: none; padding: 0; }
        li { background: #f1f1f1; padding: 10px; margin: 5px; border-radius: 5px; }
    </style>
</head>
<body>
    <h2>πŸ’¬ Multi-Client WebSocket Chat</h2>
    <input id="messageInput" type="text" placeholder="Type your message...">
    <button onclick="sendMessage()">Send</button>
    <ul id="messages"></ul>

    <script>
        const ws = new WebSocket("ws://localhost:8080");

        ws.onopen = () => {
            console.log("βœ… Connected to WebSocket Server");
        };

        ws.onmessage = (event) => {
            const msgList = document.getElementById("messages");
            const li = document.createElement("li");
            li.textContent = event.data;
            msgList.appendChild(li);
        };

        function sendMessage() {
            const input = document.getElementById("messageInput");
            if (input.value.trim()) {
                ws.send(input.value);
                input.value = "";
            }
        }
    </script>
</body>
</html>

πŸ”Ή How this works:

  • Each client can send messages.
  • Messages from one client will appear in all connected clients' chat windows!

πŸ“Œ Step 3: Running the Multi-Client WebSocket Chat

1️⃣ Start the WebSocket Server

Run the following command in the terminal:

node multi-server.js

You should see:

βœ… WebSocket Server running on ws://localhost:8080

2️⃣ Open Multiple Clients

  • Open multi-client.html in multiple browser tabs or on different devices.
  • When one client sends a message, all other clients receive it! πŸŽ‰

πŸ“Œ Step 4: Sending Private Messages Between Clients 🎯

πŸ’‘ What if we want to send messages to a specific client?

πŸ“‚ Modify multi-server.js to add private messaging:

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });
const clients = new Map(); // Store clients with unique IDs

console.log("βœ… WebSocket Server running on ws://localhost:8080");

wss.on('connection', (ws) => {
    const clientId = `User-${Math.floor(Math.random() * 1000)}`;
    clients.set(clientId, ws);

    console.log(`πŸ”— ${clientId} connected`);
    ws.send(`πŸ†” Your Client ID: ${clientId}`);

    ws.on('message', (message) => {
        console.log(`πŸ“© ${clientId} sent: ${message}`);
        
        // If message starts with @, it's a private message
        if (message.startsWith("@")) {
            const [targetId, ...msgParts] = message.split(" ");
            const targetClient = clients.get(targetId.slice(1)); // Remove @ symbol
            if (targetClient && targetClient.readyState === WebSocket.OPEN) {
                targetClient.send(`πŸ”’ Private from ${clientId}: ${msgParts.join(" ")}`);
            } else {
                ws.send(`⚠️ User ${targetId} not found.`);
            }
        } else {
            // Broadcast to everyone
            clients.forEach(client => {
                if (client !== ws && client.readyState === WebSocket.OPEN) {
                    client.send(`πŸ“’ ${clientId}: ${message}`);
                }
            });
        }
    });

    ws.on('close', () => {
        console.log(`❌ ${clientId} disconnected.`);
        clients.delete(clientId);
    });
});

πŸ“ How to send private messages?

  • Type @User-123 Hello! to send a private message to User-123.

πŸ“Œ Step 5: Running and Testing Private Messages

1️⃣ Start the WebSocket server

node multi-server.js

2️⃣ Open multi-client.html in different browser tabs
3️⃣ Check the client ID displayed on each tab
4️⃣ Send messages using @ClientID to test private messaging


🎯 Summary: What We Have Learned

βœ… Managed multiple clients using WebSockets
βœ… Broadcast messages to all clients
βœ… Implemented private messaging
βœ… Handled client disconnections

⚠️ **GitHub.com Fallback** ⚠️