Real-Time Web: Implementing a Simple JavaScript WebSocket Client
WebSockets revolutionized the web by enabling true, bi-directional, **full-duplex** communication. This means both the client and server can send data simultaneously over a single, persistent connection, perfect for chat apps and live feeds.
Unlike traditional HTTP requests where the client constantly asks the server for new data (polling), a WebSocket connection stays open, allowing the server to push updates instantly.
Step 1: Creating the Connection
The entire client connection is handled by the built-in `WebSocket` object in JavaScript. You need to use the special protocols: `ws://` (unencrypted) or `wss://` (encrypted, preferred for production).
const socket = new WebSocket('wss://your-server-domain.com/ws');
// The connection attempt starts immediately upon creation.
Step 2: Handling Core Events
The core of a WebSocket client is listening for four key events to manage the connection state:
// 1. Connection successfully established
socket.onopen = (event) => {
console.log('[open] Connection established');
socket.send("Client is connected.");
};
// 2. Message received from the server
socket.onmessage = (event) => {
console.log(`[message] Data received: ${event.data}`);
// event.data contains the incoming payload (string or binary)
};
// 3. Connection closed (cleanly or due to error)
socket.onclose = (event) => {
if (event.wasClean) {
console.log(`[close] Closed cleanly, code=${event.code}`);
} else {
console.warn('[close] Connection died unexpectedly');
}
};
// 4. An error occurred
socket.onerror = (error) => {
console.error(`[error] ${error.message}`);
};
Step 3: Sending Data
Once the connection is open (`onopen` event fires), you use the `send()` method to transmit data. This is typically done using JSON for structured data.
const userMessage = {
user: 'Alice',
text: 'Hello, world!'
};
// Convert the JavaScript object to a JSON string before sending
socket.send(JSON.stringify(userMessage));
WebSockets enable incredibly fast communication, forming the basis for modern collaborative apps, live dashboards, and trading platforms.

Comments
Post a Comment