Introduction to WebSocket APIs
In this tutorial, you will learn about Introduction to Websocket APIs. We cover key concepts, practical examples, and best practices to help you master this topic.
WebSocket provides full-duplex communication over a single TCP connection. After an initial HTTP upgrade handshake, the client and server can send messages to each other at any time, enabling low-latency real-time applications.
What You'll Learn
- WebSocket protocol fundamentals and lifecycle
- The HTTP upgrade handshake Process
- Use cases: chat, gaming, live feeds, collaborative editing
- Comparing WebSocket to HTTP polling and Server-Sent Events
Why It Matters
WebSocket enables real-time features impossible with traditional HTTP. Latency drops from polling intervals (1-30s) to milliseconds. Major platforms like Slack, Discord, and Trello use WebSocket for real-time updates.
Real-World Use
Slack uses WebSocket for message delivery. Discord uses a WebSocket-based gateway for voice and chat. Financial trading platforms stream live prices via WebSocket. Google Docs uses WebSocket for collaborative editing.
flowchart LR
Client[Client] -->|HTTP Upgrade Request| Server[Server]
Server -->|101 Switching Protocols| Client
Client <-->|Full-Duplex Messages| Server
Client -->|Close Frame| Server
Server -->|Close Frame| Client
Teacher Mindset
WebSocket is not HTTP, but it starts as HTTP. The upgrade handshake is a standard HTTP request with specific headers. After the handshake, the protocol switches to WebSocket frames over the same TCP connection.
Code Examples
// Example 1: Browser WebSocket client
const socket = new WebSocket('wss://api.example.com/chat');
socket.onopen = () => {
console.log('Connected');
socket.send(JSON.stringify({ type: 'join', room: 'general' }));
};
socket.onmessage = (event) => {
const message = JSON.parse(event.data);
console.log('Received:', message);
};
socket.onclose = () => console.log('Disconnected');
socket.onerror = (err) => console.error('Error:', err);
// Example 2: Server with ws library
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
server.on('connection', (ws, req) => {
console.log('Client connected from:', req.socket.remoteAddress);
ws.on('message', (data) => {
const message = JSON.parse(data);
ws.send(JSON.stringify({ echo: message }));
});
ws.on('close', () => console.log('Client disconnected'));
ws.send(JSON.stringify({ type: 'welcome', message: 'Connected!' }));
});
# Example 3: Testing WebSocket with wscat
wscat -c ws://localhost:8080
Connected (press CTRL+C to quit)
> {"type": "ping"}
< {"type": "pong"}
Common Mistakes
- Using WebSocket for request-response patterns that do not need real-time updates
- Not handling reconnection and connection state management on the client
- Sending plain text instead of structured JSON or binary messages
- Forgetting to close connections properly, causing resource leaks
- Not validating messages on the server before processing
Practice
- Open a WebSocket connection to a public test server (wss://echo.websocket.org).
- Send three messages and verify the echo responses.
- Implement a simple browser chat that connects to a WebSocket server.
- Handle connection drops with auto-reconnection logic.
- Challenge: Measure the latency difference between WebSocket and HTTP polling.
FAQ
Mini Project
Build a minimal WebSocket chat server that accepts connections, broadcasts messages to all connected clients, and handles disconnection gracefully. Test with browser and command-line clients.
What's Next
Next, you will learn about the HTTP-to-WebSocket upgrade process in detail.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro