HTML5 - WebSocket
HTML5 - WebSockets
Section titled “HTML5 - WebSockets”WebSockets represent a significant advancement in web communication technology, enabling full-duplex, bidirectional communication between a client (typically a web browser) and a server over a single, persistent TCP connection.
Unlike traditional HTTP request-response cycles or techniques like long-polling, WebSockets allow both the client and the server to send messages to each other at any time, once the connection is established. This makes them ideal for real-time applications like chat, live notifications, collaborative editing, multiplayer games, and financial data streaming.
The connection starts as a standard HTTP request (an ‘Upgrade’ request) and, if successful, transitions to the WebSocket protocol (ws:// or wss:// for secure connections).
The WebSocket API (Client-Side)
Section titled “The WebSocket API (Client-Side)”HTML5 provides a JavaScript API to interact with WebSocket connections. The core is the WebSocket object.
// Create a new WebSocket connection// Use wss:// for secure connections (recommended!)const socket = new WebSocket('wss://your-websocket-server.com/path');
// Optional: Specify subprotocols (server must support one)// const socket = new WebSocket('wss://your-server.com/chat', ['json', 'xml']);Here, url specifies the WebSocket server endpoint. The optional protocols argument can be a string or an array of strings specifying subprotocols the client understands.
WebSocket Attributes (Client-Side)
Section titled “WebSocket Attributes (Client-Side)”Key attributes of a WebSocket instance:
| Attribute | Description |
|---|---|
socket.readyState | Read-only attribute representing the connection state:0 (CONNECTING): Connection not yet established.1 (OPEN): Connection established, communication possible.2 (CLOSING): Connection is closing.3 (CLOSED): Connection closed or could not be opened. |
socket.bufferedAmount | Read-only attribute. Number of bytes of data queued using send() but not yet transmitted to the network. |
socket.protocol | Read-only string. The subprotocol selected by the server, if any. |
socket.url | Read-only string. The URL the WebSocket connected to. |
WebSocket Events (Client-Side)
Section titled “WebSocket Events (Client-Side)”Event handlers are crucial for interacting with the WebSocket connection:
| Event | Event Handler Property | Description |
|---|---|---|
open | socket.onopen | Fired when the connection is successfully established (readyState becomes 1). |
message | socket.onmessage | Fired when the client receives data from the server. The event object has a data property containing the received message (can be string, Blob, or ArrayBuffer). |
error | socket.onerror | Fired when there is an error in communication (e.g., connection cannot be established). |
close | socket.onclose | Fired when the connection is closed (either intentionally or due to an error). The event object provides code and reason properties. |
WebSocket Methods (Client-Side)
Section titled “WebSocket Methods (Client-Side)”Methods for managing the connection:
| Method | Description |
|---|---|
socket.send(data) | Transmits data (string, Blob, ArrayBuffer, etc.) to the server through the connection. Throws an error if the connection is not open. |
socket.close([code], [reason]) | Closes the WebSocket connection. Optional code (a status code) and reason (a string) can be provided. |
Client-Side Example
Section titled “Client-Side Example”This example demonstrates connecting, sending/receiving messages, and handling events. (Requires a running WebSocket server at wss://echo.websocket.org - a public echo server).
<!DOCTYPE html><html><head> <title>WebSocket Client Example</title></head><body> <h1>WebSocket Test</h1> <input type="text" id="messageInput" placeholder="Enter message..."> <button onclick="sendMessage()">Send Message</button> <button onclick="closeConnection()">Close Connection</button> <div id="output" style="margin-top: 10px; border: 1px solid #ccc; padding: 10px; min-height: 100px;"></div>
<script> const messageInput = document.getElementById('messageInput'); const outputDiv = document.getElementById('output'); let socket;
function log(message) { const p = document.createElement('p'); p.textContent = message; outputDiv.appendChild(p); console.log(message); }
function connectWebSocket() { if (!("WebSocket" in window)) { log("WebSocket NOT supported by your Browser!"); return; }
// Use wss:// for secure connection to the public echo server const wsUrl = 'wss://echo.websocket.org/'; log(`Attempting to connect to ${wsUrl}...`); socket = new WebSocket(wsUrl);
socket.onopen = function(event) { log("WebSocket connection opened."); // You can send an initial message here if needed // socket.send("Hello Server!"); };
socket.onmessage = function(event) { log(`Message received from server: ${event.data}`); // Handle different types of messages if necessary // const message = JSON.parse(event.data); };
socket.onclose = function(event) { log(`WebSocket connection closed. Code: ${event.code}, Reason: ${event.reason || 'N/A'}`); socket = null; // Clear reference };
socket.onerror = function(error) { log(`WebSocket Error: ${error.message || 'Unknown error'}`); console.error('WebSocket Error:', error); }; }
function sendMessage() { if (!socket || socket.readyState !== WebSocket.OPEN) { log("WebSocket is not connected."); return; } const message = messageInput.value; if (!message) return;
log(`Sending message: ${message}`); socket.send(message); // Send as string // Or send JSON: // socket.send(JSON.stringify({ type: 'chat', text: message })); messageInput.value = ''; // Clear input field }
function closeConnection() { if (socket && socket.readyState === WebSocket.OPEN) { log("Closing WebSocket connection..."); socket.close(1000, "Client closed connection"); // Normal closure } else { log("WebSocket is not open or already closed."); } }
// Automatically connect when the page loads connectWebSocket();
</script></body></html>Server-Side Implementation
Section titled “Server-Side Implementation”A WebSocket client requires a compatible server that understands the WebSocket protocol handshake and message framing.
Implementing a WebSocket server involves handling the initial HTTP Upgrade request, managing connections, and processing incoming/outgoing messages. Various libraries and frameworks exist for different backend languages (Node.js, Python, Java, C#, Go, etc.) to simplify server creation.
Conceptual Node.js Server Example (using the ‘ws’ library)
Section titled “Conceptual Node.js Server Example (using the ‘ws’ library)”This is a basic example using the popular ws library for Node.js. You would need Node.js installed and run npm install ws.
// server.js (Node.js example)const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 }); // Choose a port
console.log('WebSocket server started on port 8080');
wss.on('connection', function connection(ws) { console.log('Client connected.');
// Send a welcome message ws.send('Welcome to the WebSocket server!');
// Handle messages received from the client ws.on('message', function incoming(message) { console.log('Received from client: %s', message);
// Echo the message back to the client ws.send(`Server received: ${message}`);
// Or broadcast to all clients (example) /* wss.clients.forEach(function each(client) { if (client !== ws && client.readyState === WebSocket.OPEN) { client.send(`Broadcast: ${message}`); } }); */ });
// Handle client disconnection ws.on('close', function close() { console.log('Client disconnected.'); });
// Handle errors ws.on('error', function error(err) { console.error('WebSocket error:', err); });});To run this, save it as server.js, install the ‘ws’ library (npm install ws), and run node server.js. Then, update the client example’s wsUrl to ws://localhost:8080 (or wss:// if you configure TLS/SSL on the server, which is highly recommended for production).
Libraries like Socket.IO build upon WebSockets (and provide fallbacks) to offer additional features like rooms, automatic reconnection, and easier broadcasting, but they require using the Socket.IO client library as well.