Introduction
Real-time applications allow instant communication between clients and servers. WebSockets enable bidirectional, low-latency communication, making them ideal for chat applications, live notifications, collaborative tools, and online gaming.
1. Understanding WebSockets
WebSockets provide full-duplex communication, allowing both the client and server to send messages without the need for repeated HTTP requests.
- Uses ws:// or wss:// (secure WebSockets)
- Reduces latency compared to polling or long polling
- Efficient for real-time data streaming
2. Setting Up WebSockets in Node.js
Install WebSocket Library
npm install ws
Creating a WebSocket Server
const WebSocket = require("ws");
const server = new WebSocket.Server({ port: 8080 });
server.on("connection", (socket) => {
console.log("New client connected");
socket.send("Welcome to the WebSocket server");
socket.on("message", (message) => {
console.log("Received: ", message.toString());
socket.send("Message received: " + message);
});
socket.on("close", () => console.log("Client disconnected"));
});
3. Creating a WebSocket Client
Browser-based Client
const socket = new WebSocket("ws://localhost:8080");
socket.onopen = () => {
console.log("Connected to server");
socket.send("Hello Server!");
};
socket.onmessage = (event) => {
console.log("Message from server:", event.data);
};
socket.onclose = () => {
console.log("Connection closed");
};
4. Using WebSockets with Express
Integrating WebSockets with an Express Server
npm install express ws
const express = require("express");
const WebSocket = require("ws");
const app = express();
const server = require("http").createServer(app);
const wss = new WebSocket.Server({ server });
wss.on("connection", (socket) => {
console.log("Client connected");
socket.send("Hello from Express WebSocket");
socket.on("message", (message) => {
console.log("Received: ", message.toString());
});
});
app.get("/", (req, res) => {
res.send("WebSocket server running");
});
server.listen(3000, () => console.log("Server running on port 3000"));
5. Broadcasting Messages to Multiple Clients
Example: Sending Data to All Connected Clients
wss.on("connection", (socket) => {
socket.on("message", (message) => {
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send("Broadcast: " + message);
}
});
});
});
6. Best Practices for WebSocket Security
- Use WSS (Secure WebSockets) instead of WS
- Validate incoming messages to prevent code injection
- Implement authentication for WebSocket connections
- Limit the number of simultaneous connections
- Use a WebSocket proxy (e.g., Nginx) to enhance security
Enforcing WebSocket Authentication
wss.on("connection", (socket, req) => {
const token = req.headers["sec-websocket-protocol"];
if (!validateToken(token)) {
socket.close();
}
});
Exercises
- Set up a basic WebSocket server and test communication with a client.
- Modify the server to broadcast messages to multiple connected clients.
- Implement authentication for WebSocket connections.
- Integrate WebSockets into an Express-based API.
- Secure WebSockets by enforcing WSS and proper message validation.
Conclusion
This chapter covered WebSockets in Node.js, including setting up a WebSocket server, integrating with Express, broadcasting messages, and security best practices. In the next chapter, we will explore performance optimization techniques in Node.js applications.