TutorChase logo
Login
AQA A-Level Computer Science

18.4.14 WebSocket protocol

WebSockets enable real-time, bidirectional communication over the web by creating a full-duplex channel using a single TCP connection. They’re essential for interactive web apps.

What is the WebSocket protocol?

The WebSocket protocol is a modern web technology designed to enable full-duplex, two-way communication between a client (usually a web browser) and a server over a single, long-lived TCP connection. Unlike traditional web communication using HTTP, which follows a request-response pattern, WebSockets allow both client and server to send and receive data at any time, making it ideal for real-time applications such as live chat, online gaming, financial dashboards, and collaborative tools.

WebSockets are specified in RFC 6455, which outlines how the protocol should behave to ensure compatibility and efficiency. The protocol begins as an HTTP request and is then upgraded to a WebSocket connection through a process called the WebSocket handshake. After the upgrade, data is transmitted using a lightweight framing mechanism, which reduces overhead and improves latency.

Key features of WebSockets

  • Full-duplex communication: Both endpoints can send messages independently without waiting.

  • Single TCP connection: Only one connection is used for the entire session, avoiding the overhead of multiple HTTP connections.

  • Reduced latency: No need to repeatedly open and close connections.

  • Minimal overhead: Smaller headers and no need for repeated protocol negotiation.

  • Cross-platform support: Supported by all modern web browsers and backend environments.

How WebSockets work

Step 1: Initial handshake (HTTP upgrade)

Take your grades to the next level!

UPGRADING TO PREMIUM UNLOCKS
AI Tutor
AI-powered study assistant
instant feedback and guidance
Predicted Papers
Examiner-style predicted papers
based on recent exam trends
Practice Questions
All exam practice questions
by topic for each subject
Study Notes
All detailed revision notes
written by expert teachers
Cheat Sheets
Quick revision summaries
perfect for last-minute review
Past Papers
Complete collection
of practice and past exam papers
Email
Password
Confirm Password
Already have an account?

Practice Questions

FAQ

No, a WebSocket connection cannot be directly shared across multiple browser tabs or windows. Each tab or window operates in its own JavaScript execution context and therefore must create its own separate WebSocket connection to the server. While this is a limitation of browser environments and the WebSocket API, developers can work around it using a technique called BroadcastChannel or shared workers. These allow different tabs to communicate with each other within the same origin, and then coordinate the use of a single connection managed in one of the tabs or a background worker. However, this adds complexity and requires careful handling to manage tab closures or crashes. In most cases, it's simpler and more reliable to maintain individual WebSocket connections in each tab. Server-side logic can identify users by session or token and manage multiple concurrent connections from the same user accordingly, ensuring consistent message delivery across open contexts.

A WebSocket server distinguishes between connected clients by assigning a unique identifier to each connection, typically using a session ID, token, or connection-specific metadata. Upon connection, clients may include a unique authentication token or user ID as part of the initial handshake URL or in a message sent immediately after the connection is established. The server then associates that connection with the user’s identity or session, storing the mapping in memory or a session store. This allows the server to send targeted messages, manage individual sessions, and handle reconnections or disconnections accurately. Unlike HTTP, where each request includes headers with identifying information, WebSocket connections are persistent and require a way to associate identity once at the start. The server must maintain a connection registry that stores active connections along with relevant user data. This mechanism is essential for managing chat messages, notifications, or game states in a user-specific manner.

If a client loses internet connectivity during a WebSocket session, the TCP connection will eventually be interrupted, and the WebSocket will close. In practice, the browser or client library will detect the loss of connection and trigger the onclose or onerror event. This informs the application that the connection has ended, allowing it to respond appropriately, such as attempting to reconnect or notifying the user. Some implementations include heartbeat messages (ping/pong frames) to monitor connection health; if the server stops receiving pings or pong replies within a set interval, it assumes the connection is lost and cleans up the session. Upon reconnection, the client usually needs to re-authenticate and re-establish its state, such as rejoining chat rooms or resynchronising game data. Developers often implement automatic reconnection logic with exponential backoff delays to avoid overwhelming the server with repeated connection attempts during unstable network conditions.

Yes, browsers impose limits on the number of simultaneous WebSocket connections that can be established per domain or across all domains. These limits vary depending on the browser and version, but commonly the limit per domain ranges from 6 to 255 connections. For example, Chrome and Firefox typically allow up to 255 concurrent WebSocket connections per origin, while Internet Explorer may allow fewer. These restrictions are in place to manage memory usage and prevent abuse that could degrade browser or system performance. Additionally, operating systems and network hardware may enforce their own limits on the total number of open sockets, which can further constrain large-scale applications. Developers should design their applications with these limits in mind, using connection pooling or queuing mechanisms when multiple clients or tabs need to interact with the server. It is also good practice to close unused connections promptly and avoid opening unnecessary duplicate connections from the same client or user session.

WebSockets rely on the underlying TCP protocol to ensure ordered and reliable delivery of messages. TCP guarantees that data sent from one endpoint will arrive at the other end in the same order and without loss, unless the connection is broken. This means WebSocket messages are inherently reliable and arrive in the correct sequence as long as the connection remains intact. If messages are sent in a particular order (e.g., message A followed by B), they will be received in that same order. If a message is lost during transmission due to network issues, TCP will detect the missing data and automatically retransmit it. However, WebSocket does not provide built-in support for message acknowledgements, retries, or quality of service features like message prioritisation. If an application needs to track delivery confirmations or support higher-level message management (e.g. deduplication or ordering by timestamps), this logic must be implemented at the application layer by the developer.

Hire a tutor

Please fill out the form and we'll find a tutor for you.

1/2
Your details
Alternatively contact us via
WhatsApp, Phone Call, or Email