WebSocket is a network communication protocol that provides full-duplex communication capabilities over a single TCP connection. It is part of HTML5, allowing real-time, bidirectional interactive communication between servers and clients.
Core Features
- Full-duplex Communication: Both server and client can send and receive messages simultaneously
- Persistent Connection: Once established, the connection remains open until explicitly closed
- Low Latency: Reduces handshake and header overhead compared to HTTP polling
- Real-time: Server can proactively push data to clients
Differences from HTTP
- HTTP is request-response model, WebSocket is bidirectional communication
- HTTP connections are short-lived, WebSocket connections are persistent
- HTTP requires complete headers for each request, WebSocket requires minimal data after connection establishment
Handshake Process
WebSocket connection is established through HTTP upgrade request:
- Client sends HTTP GET request with Upgrade: websocket header
- Server returns 101 Switching Protocols response
- Connection upgrades to WebSocket protocol
Use Cases
- Real-time chat applications
- Online gaming
- Stock market data streaming
- Collaborative editing
- Real-time monitoring systems