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:.

  1. Create a WebSocket Server (Node.js)

  1. Create a WebSocket Client (Browser JavaScript)

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?