Skip to main content

Client-Server Communication Model (Part-3) - WebSockets

This is the third and final part of the Client-Server Communication Model. You can have a look at the first and second parts where we discussed different ways in which client and server can communicate. Here, we will focus on one of the most popular communication models: WebSockets.

5. WebSockets

WebSockets (RFC-6455) enable real-time, two-way, full-duplex communication between client and server over a single, long-lived connection. WebSocket, like SSE, provides a persistent connection. But in contrast to SSE, it enables full-duplex communication, which means that both client and server can communicate over the same channel. WebSockets are suitable for building interactive and dynamic applications that require continuous communication between clients and servers.

It leverages the HTTP protocol for connection establishment. Since HTTP/1.0 is a non-persistent connection, WebSocket can not be implemented on HTTP/1.0. It needs a protocol having a persistent connection, like HTTP/1.1. We have discussed why they are persistent and non-persistent in our HTTP Series.

WebSockets are stateful, in contrast to the stateless nature of the underlying HTTP protocol. Unlike HTTP, where each request-response interaction is independent and lacks information about prior requests, WebSockets ensure continuity by sustaining a continuous communication channel. This channel is initiated through a handshake, involving an HTTP request-response exchange between the client and the server. Here is the detailed flow of connection establishment:

  1. Client Requests a WebSocket Connection: 
    • The process begins with the client sending an HTTP GET request to the server, expressing its desire to establish a WebSocket connection.
    • The client includes the Connection: Upgrade header in the request, indicating that it intends to upgrade the connection to the WebSocket protocol.

  2. Server Acknowledges WebSocket Connection:
    • If the server supports WebSocket connections, it responds with a 101 status code (Switching Protocols) and includes the Connection: Upgrade header in the response.



    • The Sec-WebSocket-Accept header contains a hashed value based on the key sent by the client in the Sec-WebSocket-Key request header. This is part of the WebSocket security mechanism to prevent certain types of attacks.
  3. WebSocket Connection Established: 
    • Once the client receives the server's response, the WebSocket connection is considered established. The connection is upgraded from HTTP to the WebSocket protocol.
  4. Full-Duplex Communication: 
    • With the WebSocket connection in place, both the client and the server can send messages to each other at any time. They can exchange messages concurrently as well.
  5. WebSocket Closure: 
    • The WebSocket connection, once established, remains open until explicitly closed by either the client or the server.                                       

Advantages:

  • WebSockets provide a full-duplex communication channel, enabling real-time data exchange between the client and the server. This is especially beneficial for building interactive and dynamic applications that require continuous communication between clients and servers, such as chat applications, live notifications, and collaborative editing tools.
  • The persistent nature of WebSocket connections reduces the latency associated with connection setup and teardown, leading to faster communication. WebSockets are well-suited for applications where low-latency interaction is crucial, such as online gaming and financial trading platforms.
  • WebSockets use a binary framing format for data transfer, which is more efficient than the textual format used in traditional HTTP.
  • WebSockets can operate over secure connections (WSS), adding a layer of encryption using TLS or SSL. This ensures the confidentiality and integrity of data exchanged between the client and the server, making WebSockets suitable for secure applications.

Limitations:

  • WebSockets do not inherently provide built-in mechanisms for broadcasting messages to multiple clients. While it's possible to implement broadcasting at the application level, developers need to design their own solutions for efficiently sending messages to multiple clients.
  • Although WebSockets are supported by modern web browsers, some older browsers may not fully support the WebSocket protocol. In such cases, developers may need to implement fallback mechanisms or consider alternative communication strategies.
  • Persistent WebSocket connections can consume server resources. As the number of simultaneous connections increases, it's important to monitor resource usage and implement measures to handle scalability requirements.
  • While WebSockets maintain a persistent connection, it's important to handle scenarios where the connection is unexpectedly closed, such as due to network issues. Implementing reconnection strategies and handling connection closures is crucial for robust WebSocket applications.

Real-Life Applications:

  • WebSockets are frequently used in chat applications to enable real-time messaging between users. This includes one-on-one messaging, group chats, and chat rooms where messages are delivered instantly to all participants.
  • Applications that support real-time collaboration, such as collaborative document editing, code collaboration, and project management tools, often use WebSockets to synchronize changes among users in real-time.
  • WebSockets play a crucial role in online gaming applications, facilitating real-time communication between players and the server. This is essential for multiplayer games, where low-latency interactions are necessary for a smooth gaming experience.
  • In Internet of Things (IoT) scenarios, WebSockets are employed to establish a real-time communication channel between IoT devices and servers. This allows devices to send data or receive commands instantly.
  • WebSockets are used in online auction platforms to provide real-time bidding updates to participants. Bidders receive instant notifications about the latest bids, allowing them to respond promptly.

Comments

Popular posts from this blog

CAP Theorem - Debunking Myths

The CAP theorem is a widely recognized idea in the field of distributed systems. It represents three key concepts: Consistency, Availability, and Partition Tolerance. While most of us are familiar with its definition, the devil lies in the details. In this discussion, we'll clarify common myths and misunderstandings. We'll start by explaining the CAP theorem in detail, and then explore various scenarios that may challenge the common interpretation of it. CAP theorem also known as Brewer's theorem states that any distributed data store can provide only two of the following three guarantees: Consistency:  For every read request, the system should provide the most recent write or an error. Note that this consistency is different from the consistency of the  ACID theorem Availability:   For every request, the system should provide a response, even if it’s not the latest data.  In other words, all non-failing (healthy) nodes in the distributed system return a valid ...

Understanding Merkle Tree

A Merkle Tree is a cryptographic tree structure used in computer science and distributed systems to efficiently verify the integrity of large sets of data (accuracy and consistency of data over its lifecycle).  Merkle Tree, also known as Hash Tree is a tree of hash values.  It has a tree structure in which each leaf node is a hash of a small portion of the data, and each non-leaf node is a hash of its children. It is used in applications such as  NoSQL databases, Git, Cryptocurrencies,  File Systems, etc. Some key characteristics of Merkle Tree are: Binary Tree Structure:  The Merkle Tree is a binary tree, where each leaf node represents a hash of data. Leaf Nodes: The data set is divided into fixed-size blocks or "leaves". Each leaf node contains the hash of a specific data block or piece of information. Non-Leaf Nodes: Non-leaf nodes in the tree represent the hash of the concatenation of their child node's hashes.  If the number of leaves is odd...

Event Driven Architecture - SAGA Pattern (Part-1 : Choreography Model)

The Saga pattern is a distributed transactional pattern used in microservices architecture to maintain data consistency across multiple services. It helps manage long-running transactions involving multiple services by breaking them down into smaller, more manageable work units. There is a famous Database per Service  pattern in the Microservice world. Under this paradigm, each service maintains its own dedicated database. Some business transactions, however, span multiple services so we need a mechanism to implement transactions that span through services. Take, for instance, the scenario of placing an online order, which involves actions like inventory verification and item reservation till payment completion. Since services such as Orders, Inventory, and Payment operate on separate databases, the application cannot simply use a local ACID transaction. 2 Phase Commit Protocol  is one of the options being used for ensuring transactions across services. However, it has se...