What is WebSocket
WebSocket is a protocol that enables bidirectional real-time communication between clients and servers. It is used in applications requiring immediacy, such as chat apps, online games, and stock price displays.
WebSocket URLs:
ws://(unencrypted) andwss://(TLS encrypted) are used.
Differences Between HTTP and WebSocket
| Feature | HTTP | WebSocket |
|---|---|---|
| Communication Direction | Client → Server | Bidirectional |
| Connection | Connect/disconnect per request | Persistent |
| Server Push | Not possible | Possible |
| Overhead | HTTP headers sent every time | Only on initial connection |
| Real-time capability | Low | High |
WebSocket Handshake
# Request from client
GET /chat HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
# Response from server
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
JavaScript Implementation Example
const socket = new WebSocket('wss://example.com/chat');
socket.addEventListener('open', (event) => {
console.log('Connection successful');
socket.send('Hello Server!');
});
socket.addEventListener('message', (event) => {
console.log('Received:', event.data);
});
Socket.IO
Socket.IO is a feature-rich library based on WebSocket.
- Fallback: Uses HTTP long polling when WebSocket is unavailable
- Auto-reconnection: Automatically reconnects on disconnection
- Room feature: Groups clients together
Summary
WebSocket is a powerful protocol for enabling real-time bidirectional communication. Understanding the differences from HTTP and properly selecting and implementing it based on your application requirements is important.
← Back to list