What is WebSocket and How Does it Work

Author

Reads 1.3K

Ethernet Cables Plugged in Network Switch
Credit: pexels.com, Ethernet Cables Plugged in Network Switch

WebSockets are a way for web applications to establish a persistent, low-latency connection with a server, allowing for real-time communication between the client and server. This is achieved through a standardized protocol that enables bi-directional communication over the web.

WebSockets use a single connection to exchange data between the client and server, eliminating the need for multiple HTTP requests and responses. This results in a more efficient and scalable communication system.

The WebSocket protocol was standardized in 2011 by the Internet Engineering Task Force (IETF), and has since become a widely adopted technology for real-time web applications.

Related reading: Websocket Client in Java

What is WebSocket

WebSocket is a network protocol that provides full-duplex communication over a single, persistent TCP connection.

Unlike HTTP, which follows a request-response model, WebSockets enable continuous, low-latency, bi-directional communication between client and server.

This makes them perfect for real-time use cases like live chat applications, multiplayer gaming, and collaborative document editing.

WebSockets are ideal for applications that require instant updates and feedback, such as financial dashboards.

Here are some examples of real-time use cases that WebSockets are well-suited for:

  • Live chat applications
  • Multiplayer gaming
  • Collaborative document editing
  • IoT device updates
  • Financial dashboards

How it Works

Credit: youtube.com, WebSockets in 100 Seconds & Beyond with Socket.io

WebSocket connections start with an HTTP request from the client to the server with the Upgrade: websocket header.

The server responds with a 101 Switching Protocols status code to confirm the upgrade, marking the beginning of a persistent TCP link.

This link remains open until either the client or server closes it, allowing for continuous communication.

Both the client and server can send messages at any time without the need for separate requests, enabling full-duplex communication.

Messages are split into frames, either text or binary, and sent over the connection, minimizing overhead.

The connection stays active until one side initiates a close handshake, sending a close frame to the other side.

The other side then responds with a close frame, after which the TCP link ends.

Some key properties of WebSockets include:

  • Persistent connection (until closed)
  • Low protocol overhead
  • Full-duplex communication
  • Operates over TCP (port 80 or 443)

WebSocket Features

WebSockets provide full-duplex communication over the web, allowing for simultaneous sending and receiving of data.

This enables real-time updates and interactive web applications, making it a game-changer for web development.

Credit: youtube.com, REST API (HTTP) vs Websockets - Concept Overview With Example

Bi-directional communication is achieved through a persistent connection between the client and server, eliminating the need for frequent polling.

This reduces latency and improves overall performance.

WebSockets are supported by most modern browsers, making them a widely adopted technology.

The WebSocket API is also supported by Node.js, making it a popular choice for real-time web applications.

WebSockets can be used for a variety of applications, including live updates, chat applications, and real-time gaming.

Implementation and Support

Browser support for WebSockets is widespread, with Firefox 6, Safari 6, Google Chrome 14, Opera 12.10, and Internet Explorer 10 all implementing the secure version of the protocol.

Developers can use browser developer tools to inspect the WebSocket handshake and frames. This feature is particularly useful for debugging and testing WebSocket applications.

The table below shows the conformance of various browsers to the WebSocket protocol:

Server implementations of WebSockets are also widely available, including Nginx, Apache HTTP Server, Internet Information Services, and lighttpd.

You might enjoy: Websockets vs Sse

What is an API?

Credit: youtube.com, What Is An API In CRM Implementation? - Saas Marketing Wizards

An API, or Application Programming Interface, is essentially a set of rules that allows different software systems to communicate with each other. This enables them to exchange data and functionality in a structured way.

APIs are used to connect different systems, making it possible for them to share data and services. The WebSocket API is a great example of this, allowing web applications to open a persistent connection with a server.

The WebSocket API is supported in all modern browsers, making it a widely available and reliable option for developers. This API is the foundation of many frontend real-time applications.

APIs can be used to create a wide range of applications, from simple web services to complex enterprise software systems.

Client-to-Server Masking

Client-to-server masking is a crucial aspect of secure communication. A client must mask all frames sent to the server.

The masking process involves applying the XOR operation between the payload and the masking key. This algorithm is used to both mask and unmask frames. The pseudocode for this algorithm is provided in the relevant section.

A server, on the other hand, must not mask any frames sent to the client. This ensures that the client can receive and process the frames without any modifications.

See what others are reading: Can Audio Be Sent through Websockets

Server Implementations

Credit: youtube.com, The LockManager App Case Study: Implementing the Server Components (Part 1)

Server implementations are a crucial aspect of WebSockets. Nginx has supported WebSockets since 2013, implemented in version 1.3.13, and can act as a reverse proxy and load balancer of WebSocket applications.

Apache HTTP Server has also supported WebSockets since July 2013, implemented in version 2.4.5. Internet Information Services added support for WebSockets in version 8, which was released with Windows Server 2012.

lighttpd, a popular web server, has supported WebSockets since 2017, implemented in lighttpd 1.4.46. It can act as a reverse proxy and load balancer of WebSocket applications, and also supports WebSockets over HTTP/2 since 2022, implemented in lighttpd 1.4.65.

For .NET developers, ASP.NET Core provides support for WebSockets using the app.UseWebSockets(); middleware.

Here's a quick rundown of some popular server implementations:

Browser Support

Browser support is crucial for implementing WebSockets in your projects. A secure version of the WebSocket protocol is implemented in Firefox 6, Safari 6, Google Chrome 14, Opera 12.10, and Internet Explorer 10.

Credit: youtube.com, Checking for browser support

These browsers have undergone rigorous testing to ensure conformance to specific protocol aspects. In fact, a detailed protocol test suite report lists the conformance of these browsers to specific protocol aspects.

If you're working with older browsers, you should know that an older, less secure version of the protocol was implemented in Opera 11 and Safari 5, as well as the mobile version of Safari in iOS 4.2. The BlackBerry Browser in OS7 also implements WebSockets.

Here's a brief rundown of browser support for different versions of the WebSocket protocol:

Note that some browsers have disabled older versions of the protocol due to vulnerabilities.

Proxy Traversal

Proxy traversal is a crucial aspect of WebSocket protocol implementation. Some proxy servers can prevent WebSocket connections from working correctly, causing the connection to fail.

Transparent proxy servers can work fine with WebSocket, but explicit proxy servers without WebSockets support will likely cause the connection to fail.

Broaden your view: Websocket Proxy

Credit: youtube.com, Hunting Path Traversal in OSS

Using Transport Layer Security (TLS) in the WebSocket Secure connection ensures that an HTTP CONNECT command is issued when the browser is configured to use an explicit proxy server. This sets up a tunnel, providing low-level end-to-end TCP communication through the HTTP proxy.

Intermediate transparent proxy servers may simply allow the encrypted traffic through, giving a better chance of the WebSocket connection succeeding. Encryption is not free of resource cost, but often provides the highest success rate.

A mid-2010 draft broke compatibility with reverse proxies and gateways by including eight bytes of key data after the headers, but not advertising that data in a Content-Length: 8 header. This data was not forwarded by all intermediates, leading to protocol failure.

Managed Platform

Using a managed platform can be a game-changer for your WebSocket implementation. A managed platform like Ably provides global edge messaging infrastructure.

This means you can scale your application without worrying about the underlying infrastructure. Ably's platform is designed to handle the technical details, so you can focus on building your application.

People sitting at a conference casually checking smartphones, communicating and networking.
Credit: pexels.com, People sitting at a conference casually checking smartphones, communicating and networking.

Platforms like Ably offer client SDKs for various programming languages, including JavaScript, iOS, and Android. This makes it easier to integrate their services into your application.

Some of the key features of a managed platform like Ably include built-in pub/sub, presence, and history. These features can help you build a robust and scalable application.

Here are some of the benefits of using a managed platform:

  • Global edge messaging infrastructure
  • Client SDKs for various programming languages
  • Built-in pub/sub, presence, and history

Interface

The WebSocket API offers a robust interface for real-time communication between web applications and servers. This interface is the foundation of many frontend real-time applications.

The primary interface for connecting to a WebSocket server is provided by the WebSocket object, which allows for the exchange of data in both directions without repeated HTTP requests.

The WebSocket object provides several methods and events for managing the connection, including `ws.send(data)`, `ws.close([code] [,reason])`, `ws.onopen`, `ws.onmessage`, `ws.onclose`, and `ws.onerror`.

Here are the WebSocket object's methods and events in a concise table:

The WebSocket object's attributes provide additional information about the connection, including `ws.url`, `ws.bufferedAmount`, `ws.protocol`, `ws.extensions`, and `ws.readyState`.

Web Api

Close-up of hands using a smartphone with a heart icon on screen, representing technology and connection.
Credit: pexels.com, Close-up of hands using a smartphone with a heart icon on screen, representing technology and connection.

A web application can use the WebSocket interface to maintain bidirectional communications with a WebSocket server.

This means that a web browser can keep a continuous conversation with a server, allowing for real-time updates and interactions.

The WebSocket interface is a key part of modern web development, enabling applications to push updates directly to users.

For example, a web application can use the WebSocket interface to update a user's game score in real-time.

Most modern browsers expose the WebSocket constructor directly, making it easy to implement in web applications.

This allows developers to use the native WebSocket API, which is a more efficient and reliable way to establish real-time connections.

Readers also liked: Websocket Use Cases

Security and Performance

WebSockets can be a game-changer for real-time applications, but they come with their own set of challenges. Geographic latency, the physical distance between client and server, can impact round-trip time.

Connection scaling is another issue, as supporting thousands or millions of concurrent connections requires careful infrastructure planning. This includes handling network interruptions, ensuring message ordering, and implementing retry mechanisms.

These challenges can be tough to overcome on your own, but third-party services can help. They're built to handle WebSocket connections at scale, and can help you sidestep latency, scaling, and reliability issues.

If this caught your attention, see: Webrtc Websocket Connections

Status Codes

Credit: youtube.com, What Are Common HTTP Status Codes? - SecurityFirstCorp.com

Status codes are a crucial aspect of security and performance in web development. They help determine the outcome of a connection, indicating whether it was closed normally or abnormally.

A normal closure occurs when a connection is closed using the correct protocol, which is denoted by a status code between 1000 and 2999. This range is specifically allowed in the Close frame.

In contrast, a going away status code is triggered when a browser tab is closed or a server is shutting down, which is represented by the code 1001.

Protocol errors, such as an unsupported data type, can also be identified by a specific status code: 1002.

The code 1003 is used to indicate that the received data is not supported by the endpoint, often due to a mismatch in data types.

Some status codes are reserved for future usage, but not all of them are allowed in the Close frame. For example, code 1004 is reserved, but not allowed in the Close frame.

You might enjoy: Websocket Protocol

Credit: youtube.com, 18 Most Common HTTP Status Codes Explained in 5 Minutes

Connection closed abnormally is indicated by the status code 1006, which occurs when the closing handshake does not occur.

Invalid payload data, such as non-UTF-8 data in a text message, can be identified by the status code 1007, which is allowed in the Close frame.

A policy violation is represented by the status code 1008, which can have serious security implications.

A message that is too big can cause issues, and is indicated by the status code 1009.

Some status codes are used for specific purposes, such as 1010, which indicates that an unsupported extension was used.

Internal server errors can be identified by the status code 1011, which can be a major issue for performance.

A TLS handshake failure is represented by the status code 1015, which is not allowed in the Close frame.

Here's a summary of the status codes mentioned:

Security Considerations

Security Considerations are crucial when working with WebSockets.

Unlike regular cross-domain HTTP requests, WebSocket requests are not restricted by the same-origin policy.

Credit: youtube.com, Performance Security | Definition | Concepts | Uses & More

WebSocket servers must validate the "Origin" header against the expected origins during connection establishment.

This is to avoid cross-site WebSocket hijacking attacks, similar to cross-site request forgery.

In fact, a live example of vulnerability was seen in 2020 in the form of Cable Haunt.

It's better to use tokens or similar protection mechanisms to authenticate the WebSocket connection when sensitive data is being transferred.

A different take: Websocket Create Connection

Latency

Latency is a major concern for any application that relies on real-time communication, and WebSockets can be a game-changer in this regard.

The physical distance between client and server can impact round-trip time, which is known as geographic latency. This is a crucial factor to consider when it comes to minimizing latency.

Supporting thousands or millions of concurrent connections requires careful infrastructure planning, which can be a daunting task for developers.

Here are some key factors that can impact latency:

  • Geographic latency: The physical distance between client and server can impact round-trip time.
  • Connection scaling: Supporting thousands or millions of concurrent connections requires careful infrastructure planning.

By understanding these factors, you can take steps to minimize latency and ensure a seamless user experience.

Alternatives and Comparison

Credit: youtube.com, REST API (HTTP) vs Websockets - Concept Overview With Example

WebSockets are often just one of several protocol options available for building a real-time application. Each alternative has its own strengths and weaknesses depending on your use case.

For example, Server-Sent Events (SSE) are great for one-way updates, but they're not bidirectional and don't support binary data.

WebSockets, on the other hand, are perfect for real-time messaging and chat, but they don't have built-in fallback or ordering.

gRPC is well-suited for microservices and API streaming, but it has limited browser support.

HTTP/2 is efficient for REST delivery, but it's still a request-response protocol.

MQTT is ideal for IoT/embedded devices, but it requires complex broker management.

Here's a comparison of these protocols in a table:

Ultimately, choosing the right protocol often comes down to the needs of your architecture, scale, and engineering resources.

Getting Started

To start building with WebSockets, you can use the native WebSocket API, which is exposed directly in most modern browsers.

The WebSocket constructor is used to start the opening handshake, and it takes two arguments: the URL of the WebSocket server and an optional list of protocols.

Credit: youtube.com, Learn Socket.io In 30 Minutes

You can use the WebSocket constructor like this: `ws = new WebSocket(url [, protocols])`.

The WebSocket interface has several methods and properties that you can use to interact with the WebSocket connection. Here are the main ones:

To listen to events, you can use the `addEventListener()` method or assign an event listener to the `oneventname` property of the WebSocket interface.

Some common events include `open`, `message`, `close`, and `error`.

Applications of WebSocket

WebSocket applications are all around us, making our lives more convenient and efficient.

Many popular messaging apps use WebSockets for instant messaging sync between browser and phone, such as WhatsApp Web, Slack, and Facebook Messenger.

Google Docs is another great example of WebSocket in action, allowing for collaborative document editing where changes appear instantly.

Live presence indicators, chat messages, and meeting controls are also enabled by WebSockets in platforms like Zoom and Microsoft Teams.

TradingView uses WebSockets to provide real-time stock, crypto, and forex price updates, helping traders make informed decisions.

Uber's live driver location and ride status updates are also made possible by WebSockets.

Online multiplayer games are another area where WebSockets shine, enabling low-latency player interactions in many browser-based games.

Technical Details

Credit: youtube.com, How Web Sockets work | Deep Dive

WebSockets are bi-directional, meaning they allow for simultaneous communication between a client and a server.

They use the WebSocket protocol, which is based on the TCP/IP protocol and establishes a persistent connection between the client and server.

This connection is maintained through a handshake process, where the client sends a request to the server to upgrade the connection to a WebSocket connection.

The WebSocket protocol is defined in RFC 6455, which outlines the rules for establishing and maintaining a WebSocket connection.

A WebSocket connection is established by sending a WebSocket handshake request from the client to the server, which includes the "Upgrade" header and the "Sec-WebSocket-Version" header.

For your interest: Sec Websocket Protocol

Frequently Asked Questions

What is the difference between WebSocket and hook?

WebSockets enable real-time, continuous communication, whereas webhooks are better suited for event-driven notifications with lower frequency. The choice between the two depends on your application's specific needs.

How do you connect to a WebSocket?

To connect to a WebSocket, create a WebSocket object with the server's URL and protocols. This will automatically initiate a connection to the server, allowing real-time communication.

Is WSS the same as https?

WSS (WebSocket Secure) is similar to HTTPS, but specifically designed for real-time communication between a client and server. While both use encryption, WSS focuses on bidirectional communication over a persistent connection.

Are WebSockets overkill?

WebSockets may be overkill for web applications with low real-time requirements or minimal client-server interaction. Consider using WebSockets for real-time, bidirectional communication in applications that demand instant updates.

How to change ws to wss?

To secure a WebSocket connection, place it behind an SSL-enabled proxy server, such as Apache or Nginx, which will redirect requests to a secure WSS connection. This approach is commonly used to secure bootnodes and RPC servers.

Mona Renner

Senior Copy Editor

Mona Renner is a meticulous and detail-driven Copy Editor with a passion for refining complex concepts into clear and concise language. With a keen eye for grammar and syntax, she has honed her skills in editing articles across a range of technical topics, including Google Drive APIs. Her expertise lies in distilling technical jargon into accessible and engaging content that resonates with diverse audiences.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.