| # WebSocket Protocol |
|
|
| ## What is WebSocket? |
|
|
| WebSocket provides full-duplex communication channels over a single TCP connection. Unlike HTTP, WebSocket allows real-time bidirectional communication. |
|
|
| ## Connection Flow |
|
|
| ``` |
| Client Server |
| │ │ |
| │──── HTTP Upgrade Request ────▶│ |
| │ Upgrade: websocket │ |
| │ │ |
| │◀─── HTTP 101 Switching -------│ |
| │ Protocol: ws │ |
| │ │ |
| │◀═════ WebSocket Open ═════════▶│ |
| │ │ |
| │◀═════ Messages ══════════════▶│ |
| │ │ |
| │◀═════ Connection Close ═══════▶│ |
| ``` |
|
|
| ## WebSocket Headers |
|
|
| ### Upgrade Request |
| ``` |
| GET /ws HTTP/1.1 |
| Host: api.example.com |
| Upgrade: websocket |
| Connection: Upgrade |
| Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== |
| Sec-WebSocket-Version: 13 |
| ``` |
|
|
| ### Server Response |
| ``` |
| HTTP/1.1 101 Switching Protocols |
| Upgrade: websocket |
| Connection: Upgrade |
| Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= |
| ``` |
|
|
| ## Implementation Examples |
|
|
| ### Server (Node.js + ws) |
| ```javascript |
| const WebSocket = require('ws'); |
| const wss = new WebSocket.Server({ port: 8080 }); |
| |
| wss.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'); |
| }); |
| |
| // Send periodic message |
| const interval = setInterval(() => { |
| ws.send('Ping: ' + Date.now()); |
| }, 30000); |
| |
| ws.on('close', () => clearInterval(interval)); |
| }); |
| ``` |
|
|
| ### Client (Browser) |
| ```javascript |
| const ws = new WebSocket('ws://localhost:8080'); |
| |
| ws.onopen = () => { |
| console.log('Connected to WebSocket'); |
| ws.send('Hello Server!'); |
| }; |
| |
| ws.onmessage = (event) => { |
| console.log('Received:', event.data); |
| }; |
| |
| ws.onerror = (error) => { |
| console.error('WebSocket error:', error); |
| }; |
| |
| ws.onclose = () => { |
| console.log('Disconnected'); |
| }; |
| ``` |
|
|
| ### Client (Python) |
| ```python |
| import asyncio |
| import websockets |
| |
| async def main(): |
| async with websockets.connect('ws://localhost:8080') as ws: |
| await ws.send('Hello Server!') |
| response = await ws.recv() |
| print(f"Received: {response}") |
| |
| asyncio.run(main()) |
| ``` |
|
|
| ## Socket.IO (Higher Level) |
|
|
| ### Server |
| ```javascript |
| const { Server } = require('socket.io'); |
| const io = new Server(3000, { |
| cors: { origin: '*' } |
| }); |
| |
| io.on('connection', (socket) => { |
| console.log('User connected:', socket.id); |
| |
| socket.on('message', (data) => { |
| console.log('Message:', data); |
| io.emit('message', data); |
| }); |
| |
| socket.on('disconnect', () => { |
| console.log('User disconnected'); |
| }); |
| |
| socket.on('join-room', (room) => { |
| socket.join(room); |
| socket.to(room).emit('user-joined', socket.id); |
| }); |
| }); |
| ``` |
|
|
| ### Client |
| ```javascript |
| import { io } from 'socket.io-client'; |
| |
| const socket = io('http://localhost:3000'); |
| |
| socket.on('connect', () => { |
| console.log('Connected:', socket.id); |
| socket.emit('message', 'Hello everyone!'); |
| }); |
| |
| socket.on('message', (data) => { |
| console.log('Received:', data); |
| }); |
| ``` |
|
|
| ## WebSocket vs HTTP |
|
|
| | Aspect | WebSocket | HTTP | |
| |--------|----------|------| |
| | Connection | Persistent | Request-Response | |
| | Direction | Bidirectional | Client → Server | |
| | Overhead | Low (after handshake) | High (headers each request) | |
| | Use Case | Real-time apps | REST APIs, simple requests | |
| | Browser Support | Modern browsers | All browsers | |
|
|
| ## Best Practices |
|
|
| 1. **Heartbeat/Ping-Pong** - Keep connections alive |
| 2. **Reconnection Logic** - Handle connection drops |
| 3. **Message Queueing** - Queue messages during disconnect |
| 4. **Authentication** - Validate on connection |
| 5. **Rate Limiting** - Prevent abuse |
| 6. **Compression** - Consider permessage-deflate |
|
|