What is WebSocket?
WebSocket enables persistent, bidirectional, real-time communication between clients and servers over a single connection.
WebSocket is a protocol that enables two-way, real-time communication between a client and server. Unlike HTTP where the client always initiates requests, WebSocket allows both sides to send messages anytime. It's like upgrading from walkie-talkies (HTTP) to a phone call (WebSocket) — you can talk and listen simultaneously.
How It Works:
- Handshake: Client sends HTTP request asking to upgrade to WebSocket
- Connection: Server accepts, connection upgrades to WebSocket
- Persistent: Connection stays open (unlike HTTP's request-response)
- Bidirectional: Both client and server can send messages
- Real-time: Messages arrive instantly
WebSocket vs HTTP:
- HTTP: Request-response, client initiates, stateless
- WebSocket: Persistent connection, bidirectional, stateful
When to Use WebSocket:
- Real-time chat: Instant messaging
- Live updates: Stock prices, sports scores
- Collaborative editing: Multiple users editing together
- Gaming: Real-time multiplayer
- Notifications: Push notifications to browser
Benefits:
- Low latency: No HTTP overhead per message
- Efficient: Persistent connection, less overhead
- Real-time: Instant communication
FAQ
When should I use WebSocket vs HTTP?
Use HTTP for request-response patterns. Use WebSocket when you need real-time, bidirectional communication or server-initiated messages.
Are WebSockets secure?
WebSocket (ws://) is not encrypted. Use WSS (WebSocket Secure, wss://) for encrypted connections, similar to HTTPS.