What is WebSocket
Bidirectional browser-server connection
WebSocket is a communication protocol that provides a persistent bidirectional connection between client and server in real-time.
How It Works
- Handshake — initial HTTP handshake
- Upgrade — switching to WebSocket protocol
- Full-duplex — simultaneous transmission in both directions
- Persistent connection — no repeated connections
Advantages Over HTTP
- Instant message delivery
- Minimal overhead
- No need for polling
- Low latency
Applications
- Chats and messengers
- Online games
- Stock quotes
- Collaborative editing
- IoT devices
Technologies
- Socket.IO (Node.js)
- ws (Node.js native)
- SignalR (.NET)
- Django Channels
Example
const ws = new WebSocket('wss://api.example.com');
ws.onmessage = (event) => {
console.log(event.data);
};
ws.send('Hello Server!');