WebSocket is a network communication protocol that provides full-duplex communication capabilities over a single TCP connection. It is part of HTML5 and enables real-time, bidirectional interactive communication between servers and clients.
Main Differences from HTTP
1. Communication Mode
- HTTP: Half-duplex communication, client initiates request, server responds then connection closes
- WebSocket: Full-duplex communication, both parties can send and receive data simultaneously
2. Connection Persistence
- HTTP: Stateless protocol, each request requires establishing a new connection
- WebSocket: Persistent connection, can maintain long-term communication after establishment
3. Protocol Overhead
- HTTP: Each request includes complete HTTP headers, high overhead
- WebSocket: After connection establishment, data frame headers are very small (2-14 bytes), minimal overhead
4. Real-time Performance
- HTTP: Requires polling or long-polling for real-time communication, higher latency
- WebSocket: Server can actively push data, strong real-time capability
WebSocket Protocol Features
Handshake Process
WebSocket establishes connection through HTTP upgrade mechanism:
shellClient Request: GET /chat HTTP/1.1 Host: server.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=
Data Frame Format
WebSocket uses lightweight data frame format, supporting both text and binary data transmission.
Application Scenarios
- Real-time chat applications
- Online gaming
- Stock market data streaming
- Collaborative editing
- Real-time monitoring and dashboards