WebSockets
WebSockets provide a persistent, full-duplex communication channel over a single TCP connection. Unlike HTTP, where the client must initiate every request, WebSockets allow the server to send data to the client at any time.
1. The Concept: Full-Duplex
- HTTP (Half-Duplex/Request-Response): The client sends a request, the server sends a response, and the connection closes (stateless). To get new data, the client must ask again (polling).
- WebSocket (Full-Duplex): The client and server establish a connection once. After that, both parties can send data back and forth freely until one side closes the connection.
2. The Handshake
A WebSocket connection starts as a standard HTTP request.
- Client: Sends an HTTP GET request to the server with an
Upgrade: websocketheader. - Server: If it supports WebSockets, it responds with
101 Switching Protocols. - Connection: The HTTP connection is replaced by a WebSocket connection running over the same underlying TCP/IP connection.
3. Use Cases
WebSockets are ideal for Real-Time Applications:
- Chat Applications (WhatsApp, Slack)
- Live Sports Scores / Stock Tickers
- Multiplayer Online Games
- Collaborative Editing (Google Docs)
4. Implementation Example
Client-Side (Browser)
Modern browsers have a built-in WebSocket API.
// Create connection
const socket = new WebSocket('ws://localhost:8080');
// Connection opened
socket.addEventListener('open', (event) => {
socket.send('Hello Server!');
});
// Listen for messages
socket.addEventListener('message', (event) => {
console.log('Message from server:', event.data);
});
Server-Side (Node.js with ws library)
While Node.js doesn't have built-in WebSockets, libraries like ws or socket.io are commonly used.
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function message(data) {
console.log('received: %s', data);
});
ws.send('something');
});