WebSocket

What is WebSocket?

WebSocket is a communication protocol that provides full-duplex, real-time communication between a client and a server over a single TCP connection. Unlike traditional HTTP, which follows a request-response model, WebSockets enable continuous bidirectional communication, making them ideal for chat applications, live notifications, gaming, and stock market updates.

How WebSockets Work

  1. Handshake – The client sends an HTTP request to upgrade the connection to WebSocket.

  2. Connection Establishment – The server accepts the request, and both establish a persistent WebSocket connection.

  3. Bidirectional Communication – The client and server can now send messages anytime without waiting for a response.

  4. Connection Closure – Either side can close the connection when needed.

WebSocket Architecture

  • Client – A web browser or app initiating a WebSocket connection.

  • WebSocket Server – Manages connections and routes messages.

  • Message Transport – The WebSocket protocol sends messages over a single connection.

WebSocket Example (Node.js & JavaScript)

Let's create a WebSocket server and a WebSocket client.

1. Install WebSocket Library

Run the following command to install WebSocket support:.

npm install ws
  1. Create a WebSocket Server (Node.js)

const WebSocket = require('ws');

const server = new WebSocket.Server({ port: 8080 });

server.on('connection', (socket) => {
    console.log('New client connected');

    socket.on('message', (message) => {
        console.log(`Received: ${message}`);
        socket.send(`Server received: ${message}`);
    });

    socket.on('close', () => {
        console.log('Client disconnected');
    });
});

console.log('WebSocket server is running on ws://localhost:8080');
  1. Create a WebSocket Client (Browser JavaScript)

const socket = new WebSocket('ws://localhost:8080');

socket.onopen = () => {
    console.log('Connected to WebSocket server');
    socket.send('Hello, Server!');
};

socket.onmessage = (event) => {
    console.log(`Message from server: ${event.data}`);
};

socket.onclose = () => {
    console.log('Disconnected from WebSocket server');
};

WebSocket Events:

Event
Description

onopen

Triggered when the WebSocket connection is established.

onmessage

Triggered when a message is received from the server.

onerror

Triggered when an error occurs.

onclose

Triggered when the connection is closed.

WebSocket Use Cases

  • Live Chat Applications – Instant messaging with real-time updates.

  • Stock Market Feeds – Live updates of stock prices.

  • Online Gaming – Multiplayer games with real-time interactions.

  • Live Sports Scores – Streaming real-time game updates.

  • Collaboration Tools – Google Docs-style real-time editing.

Disadvantages of WebSockets

  • Firewall Issues – Some corporate networks block WebSocket connections.

  • Scalability – Managing multiple open WebSocket connections can be resource-intensive.

  • Complexity – More difficult to implement than traditional HTTP requests.

When to Use WebSockets?

  • Need real-time updates (Chat apps, stock tickers, notifications).

  • Frequent two-way communication (Gaming, live streaming).

  • Reduce latency (Instant response without polling the server).

Conclusion

WebSockets provide an efficient, low-latency communication channel for real-time applications. They outperform HTTP when continuous, bidirectional data flow is required.

Last updated

Was this helpful?