What is WebSocket?
WebSocket is a communication protocol that provides full-duplex communication channels over a single TCP connection. It is designed to enable real-time, bi-directional data transfer between a client (typically a web browser) and a server, making it a powerful tool for applications requiring instant updates and persistent connections.
Core Concept
Unlike traditional HTTP requests, which are stateless and involve the client initiating a new request for each piece of data, WebSocket establishes a persistent, long-lived connection between the client and server. Once the connection is established, both parties can send messages to each other at any time, without needing to re-establish the connection for each message.
Key Features
- Full-Duplex Communication: Allows two-way communication where both client and server can send and receive messages simultaneously.
- Persistent Connection: Maintains a single, long-lived connection, eliminating the overhead of repeatedly establishing new connections.
- Lower Overhead: After the initial handshake, WebSocket communication uses a minimal frame header, resulting in less data overhead compared to HTTP polling.
- Real-time Data Transfer: Enables instant delivery of data, crucial for applications requiring immediate updates.
- Browser Compatibility: Widely supported by modern web browsers, making it accessible for web-based applications.
How it Works (Simplified)
1. Handshake: The process begins with an HTTP-based handshake. The client sends a regular HTTP request to the server, but includes special 'Upgrade' and 'Connection' headers, indicating a desire to switch to the WebSocket protocol. 2. Upgrade: If the server supports WebSocket, it responds with an HTTP 101 Switching Protocols status, confirming the protocol upgrade. 3. Persistent Connection: Once the handshake is complete, the underlying TCP connection is upgraded from HTTP to WebSocket. From this point on, all communication uses the WebSocket protocol frames, and the connection remains open until explicitly closed by either the client or the server.
Use Cases
- Real-time Chat Applications: Instant messaging and group chats.
- Live Sports Scores/Stock Tickers: Continuous updates of rapidly changing data.
- Multiplayer Online Gaming: Synchronizing game states between players and servers.
- Collaborative Editing Tools: Real-time document editing (e.g., Google Docs).
- Notifications: Push notifications to users without polling.
- IoT Devices: Bi-directional communication with Internet of Things devices.
Example (Client-side JavaScript)
Here's a basic example of how to connect to a WebSocket server and handle messages using JavaScript in a browser.
// Create a new WebSocket connection
const socket = new WebSocket('ws://localhost:8080');
// Connection opened
socket.addEventListener('open', (event) => {
console.log('WebSocket connection opened:', event);
socket.send('Hello Server!');
});
// Listen for messages
socket.addEventListener('message', (event) => {
console.log('Message from server:', event.data);
});
// Listen for possible errors
socket.addEventListener('error', (event) => {
console.log('WebSocket error:', event);
});
// Connection closed
socket.addEventListener('close', (event) => {
console.log('WebSocket connection closed:', event);
});
// Example of sending a message after 3 seconds
setTimeout(() => {
if (socket.readyState === WebSocket.OPEN) {
socket.send('Another message from client!');
}
}, 3000);
// Example of closing the connection after 5 seconds
setTimeout(() => {
if (socket.readyState === WebSocket.OPEN) {
socket.close();
}
}, 5000);