Multiple Clients - potatoscript/websocket GitHub Wiki
π‘ Imagine building a chatroom, a multiplayer game, or a collaborative document editorβall of these require managing multiple WebSocket clients efficiently.
- 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 π―
π 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 aSet
. -
ws.on('message', β¦)
listens for messages from clients. -
broadcastMessage()
sends messages to all connected clients.
π 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!
Run the following command in the terminal:
node multi-server.js
You should see:
β
WebSocket Server running on ws://localhost:8080
- Open
multi-client.html
in multiple browser tabs or on different devices. - When one client sends a message, all other clients receive it! π
π‘ 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 toUser-123
.
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
β
Managed multiple clients using WebSockets
β
Broadcast messages to all clients
β
Implemented private messaging
β
Handled client disconnections