Introduction to WebSocket
In this tutorial, you will learn about Introduction to WebSocket. We cover key concepts, practical examples, and best practices to help you master this topic.
WebSocket is a protocol that enables full-duplex, bidirectional communication over a single TCP connection. Unlike HTTP request-response, WebSocket allows servers to push data to clients in real time.
What You'll Learn
- What WebSocket is and how it works
- How WebSocket differs from HTTP
- Common use cases for WebSocket
- WebSocket protocol overview
- When to use WebSocket vs alternatives
Why It Matters
Users expect real-time experiences. WebSocket enables live updates, instant messaging, and real-time collaboration that traditional HTTP cannot efficiently provide.
Real-World Use
A financial trading platform uses WebSocket to stream real-time stock prices. Thousands of clients receive price updates within milliseconds of any market change, enabling split-second trading decisions.
Flow Chart
flowchart LR
A[Client] -->|HTTP Upgrade Request| B[Server]
B -->|101 Switching Protocols| A
A <-->|Full-Duplex| B
B -->|Push Data| A
A -->|Send Data| B
Code Examples
Example 1: Basic WebSocket Client in JavaScript
const ws = new WebSocket('wss://echo.example.com');
ws.onopen = () => {
console.log('Connected');
ws.send('Hello Server!');
};
ws.onmessage = (event) => {
console.log('Received:', event.data);
ws.close();
};
ws.onclose = () => {
console.log('Disconnected');
};
ws.onerror = (error) => {
console.error('Error:', error);
};
Expected output: Client connects to server, sends a message, receives the echo response, and closes the connection.
Example 2: WebSocket Server in Node.js
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
server.on('connection', (ws) => {
console.log('Client connected');
ws.on('message', (message) => {
console.log('Received:', message.toString());
ws.send(`Echo: ${message}`);
});
ws.on('close', () => {
console.log('Client disconnected');
});
ws.send('Welcome to the WebSocket server!');
});
console.log('WebSocket server running on ws://localhost:8080');
Expected output: Server logs client connections, echoes messages back, and sends welcome message on connection.
Example 3: WebSocket vs HTTP Polling Comparison
// HTTP polling approach
async function pollForUpdates() {
setInterval(async () => {
const response = await fetch('/api/updates');
const data = await response.json();
console.log('Updates:', data);
}, 2000);
}
// WebSocket approach
function connectWebSocket() {
const ws = new WebSocket('wss://server.example.com/updates');
ws.onmessage = (event) => {
console.log('Real-time update:', event.data);
};
}
Expected output: HTTP polling sends requests every 2 seconds even without updates. WebSocket delivers updates instantly only when data changes.
Common Mistakes
| Mistake | Explanation |
|---|---|
| Using HTTP for real-time features | HTTP polling wastes bandwidth; use WebSocket for push-based communication |
| Ignoring connection lifecycle | Always handle onopen, onmessage, onclose, and onerror events |
| Not handling reconnection | Network interruptions happen; implement automatic reconnection |
| Mixing HTTP and WebSocket ports | WebSocket often uses a different port or path than HTTP endpoints |
| Sending unformatted data | Use JSON or a consistent Serialization format for all messages |
Practice Questions
- What is the main difference between HTTP and WebSocket?
- How does a WebSocket connection start?
- What are common use cases for WebSocket?
- What happens when a WebSocket connection drops?
- How does WebSocket handle binary vs text data?
Challenge
Create a WebSocket echo server and client. The client should send 10 messages with 1-second intervals, receive echo responses, and log the round-trip time for each message. Include automatic reconnection if the server restarts.
FAQ
Mini Project
Build a real-time server monitoring dashboard. The server pushes CPU, memory, and disk usage metrics via WebSocket every second. The client displays live-updating charts showing system resource utilization.
What's Next
Learn about the WebSocket HTTP upgrade handshake
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro