HTML5 WebSocket
WebSocket is the next generation of client-server communication technology. It provides a full-duplex communication channel over a single TCP connection, meaning both client and server can send data to each other at any time, enabling true real-time, bidirectional communication.
This stands in stark contrast to the traditional HTTP request-response model. In HTTP, communication is always initiated by the client, and the server can only passively respond. WebSocket breaks this limitation.
Advantages of WebSocket
- True bidirectional communication: Both client and server can actively send data to each other.
- Low latency: Once the connection is established, data exchange no longer requires sending heavy HTTP headers, greatly reducing overhead and latency.
- Persistent connection: The connection stays open until one party explicitly closes it.
WebSocket is ideal for applications requiring high-frequency, low-latency data exchange, such as:
- Online multiplayer games
- Real-time chat applications
- Collaborative editing tools (like Google Docs)
- Real-time data feeds for financial applications
Client Implementation
Using WebSocket on the client side is very straightforward. You need to create a WebSocket object and provide a special ws or wss (secure) protocol URL.
1. Creating a WebSocket Connection
// Create a WebSocket instance
// 'ws://' is the unencrypted protocol, 'wss://' is encrypted
const socket = new WebSocket('ws://www.example.com/socketserver');2. WebSocket Events
The WebSocket object has four core events:
onopen: Triggered when the connection to the server is successfully established.javascriptsocket.onopen = function(event) { console.log('Connection established!'); // After connection is established, you can start sending messages to the server socket.send('Hello, Server!'); };onmessage: Triggered when a message is received from the server. The message content is inevent.data.javascriptsocket.onmessage = function(event) { console.log('Message received: ' + event.data); };onclose: Triggered when the connection is closed.javascriptsocket.onclose = function(event) { if (event.wasClean) { console.log(`Connection closed cleanly, code=${event.code} reason=${event.reason}`); } else { // e.g., server process killed or network down console.log('Connection died unexpectedly'); } };onerror: Triggered when a communication error occurs.javascriptsocket.onerror = function(error) { console.log(`[error] ${error.message}`); };
3. Sending Messages and Closing the Connection
socket.send(data): Sends data to the server. Data can be strings, Blobs, ArrayBuffers, etc.socket.close([code], [reason]): Closes the connection.
Server-Side Implementation
WebSocket requires dedicated server-side support because it's not standard HTTP. The server must understand the WebSocket "handshake" request and "upgrade" the HTTP connection to a WebSocket connection.
Many backend languages and frameworks provide WebSocket libraries, such as:
- Node.js:
ws,Socket.IO - Python:
websockets,Tornado - Java:
JSR 356,Spring Framework - Go:
gorilla/websocket
Server-side logic typically involves: listening for connections, receiving messages from specific clients, then deciding whether to broadcast messages to all other clients (like in a chat room) or just reply to the original client.