WebSocket: What It Is, Full-Duplex Communication Protocol and How It Works

Author: IT Sectr Published: 2026-03-06 Reading time: 8 min

WebSocket is a full-duplex communication protocol that establishes a persistent connection between a client and a server for real-time data exchange. Unlike traditional HTTP requests, this protocol sets up a single connection and uses it for bidirectional transmission without repeated handshakes. According to Mozilla Developer Network (2025), WebSocket reduces latency by up to 50% compared to HTTP polling in real-time applications.

Key Takeaways

  • WebSocket is a full-duplex protocol over TCP for real-time data exchange
  • Persistent connection eliminates the overhead of repeated HTTP handshakes with each request
  • Latency is reduced by 30-50% compared to HTTP Long Polling due to the absence of headers
  • The protocol is supported by all modern browsers and mobile platforms through native APIs
  • Applications include chats, online games, trading terminals, and IoT devices

What is WebSocket?

WebSocket is a communication protocol operating over TCP that provides a full-duplex channel between a client and a server. It was standardized by the IETF as RFC 6455 in 2011 and is supported by all modern browsers, mobile platforms, and server frameworks.

Unlike HTTP, where the client initiates a request and receives a response, WebSocket allows both sides to send messages at any time after the connection is established. This makes it ideal for scenarios requiring instant delivery of data: chats, notifications, collaborative document editing.

The WebSocket protocol uses HTTP port 80 or HTTPS port 443 for the initial handshake, after which it switches to its own protocol with a minimal header — only 2 bytes instead of 800+ bytes in HTTP. This feature provides a significant performance advantage with a large number of messages.

Key Protocol Characteristics

A WebSocket connection begins with an HTTP upgrade request (Upgrade), after which the protocol switches to a binary frame format. The frame size ranges from 2 bytes to 2^63 bytes, allowing transmission of both short text messages and large binary data. The protocol supports message fragmentation, data masking from client to server, and ping/pong for connection keep-alive.

How Does WebSocket Work?

The WebSocket connection setup process consists of two stages: handshake and data transfer. During the handshake stage, the client sends an HTTP request with the Upgrade: websocket header, and the server confirms the protocol switch with status 101 Switching Protocols. After this, the connection enters full-duplex transmission mode.

Each message in WebSocket is divided into frames. A frame contains an opcode (text, binary data, close, ping/pong), payload length, and a masking key for data from the client. Frames can be fragmented — control frames (ping/pong) can be transmitted between message fragments, preventing connection timeout during long transfers.

js
const ws = new WebSocket('wss://example.com/chat')

ws.addEventListener('open', () => {
    console.log('Connection established')
    ws.send('Hello, server!')
})

ws.addEventListener('message', (event) => {
    console.log('Received:', event.data)
})

ws.addEventListener('close', () => {
    console.log('Connection closed')
})

In the example above, the client creates a WebSocket object specifying the secure URL wss://. After the connection opens, a welcome message is sent, and the message handler receives responses from the server. On close, the close handler fires — this is important for reconnection in case of network interruptions.

WebSocket vs HTTP: Comparison

The main difference between WebSocket and HTTP lies in the interaction model. HTTP operates on a request-response scheme: the client initiates a request, the server returns a response, and the connection is closed. WebSocket, on the other hand, establishes a persistent channel through which both sides can initiate transmission at any time.

For applications requiring low latency and a constant stream of data, WebSocket is significantly more efficient. HTTP Long Polling — an alternative where the server holds the request open until data becomes available — creates excessive server load and increases memory consumption due to multiple concurrent connections.

ParameterWebSocketHTTP
ModelFull-duplexRequest-response
Header2-14 bytes400-800 bytes
Persistent connectionYes, singleNo, new per request
LatencyLow (1-5 ms)High (50-200 ms)
Protocolws:// or wss://http:// or https://

According to High Performance Browser Networking (Grigorik, O'Reilly), WebSocket reduces network latency in real-time scenarios by 40-60% compared to HTTP Long Polling, while server load is reduced by 3-5 times due to the elimination of repeated handshakes.

Where WebSocket Is Used

Thanks to its low latency and bidirectional communication, WebSocket is used in a wide range of applications. Key scenarios include instant messaging, state synchronization in games, and market data transmission in financial systems.

Chats and Messengers

WebSocket has become the de facto standard for chat applications. Platforms such as Slack, Telegram Web, and WhatsApp Web use WebSocket for instant message delivery. The protocol allows sending both text messages and files through a single channel, while the ping/pong mechanism keeps the connection active even during periods of inactivity.

Online Games

Multiplayer browser and mobile games require minimal latency for synchronizing player states. WebSocket transmits coordinates, actions, and events in real time without the delays of HTTP requests. Frameworks like Socket.IO and Colyseus abstract low-level protocol operations, adding automatic reconnection and rooms.

Financial Applications

Trading terminals and trading platforms use WebSocket to receive real-time quotes. A delay of a few milliseconds can cost millions of dollars, so financial APIs — such as Binance WebSocket Streams, Coinbase Pro — provide WebSocket interfaces for market data.

Mobile Applications and IoT

In mobile development, WebSocket is used through native APIs: URLSessionWebSocketTask on iOS and OkHttp WebSocket on Android. For Flutter, there is the web_socket_channel library, and for React Native — react-native-websocket. IoT devices use WebSocket for transmitting telemetry and receiving control commands, as the protocol consumes less energy than constant HTTP polling.

WebSocket Code Examples

Let us look at a server-side example using Node.js with the ws library — the most popular WebSocket implementation for JavaScript. The server accepts connections, processes messages, and broadcasts them to all connected clients.

js
const WebSocket = require('ws')
const wss = new WebSocket.Server({ port: 8080 })

wss.on('connection', (ws) => {
    console.log('New client connected')

    ws.on('message', (data) => {
        console.log('Received:', data.toString())
        ws.send('Server received your message')
    })

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

console.log('WebSocket server started on port 8080')

The server creates a WebSocket.Server instance on port 8080 and waits for connections. Each new client is assigned a separate ws object through which the server can send individual messages. Broadcasting messages to all clients is implemented by iterating through the array of connections. With a large number of clients (over 1000), it is recommended to use libraries with clustering support, such as Socket.IO, which add Redis-based scaling and automatic reconnection.

Sending Messages to All Clients

js
wss.clients.forEach((client) => {
    if (client.readyState === WebSocket.OPEN) {
        client.send('Message for all participants')
    }
})

Checking readyState before sending is mandatory: if the client has already disconnected, calling send will throw an error. The WebSocket.OPEN flag ensures the connection is active and the message will be delivered.

For iOS mobile applications, WebSocket is implemented through URLSessionWebSocketTask, available since iOS 13. The session creates a task with a wss:// protocol URL, after which the send and receive methods are called. Receiving messages can be organized through continuous receive recursion, which waits for the next message after processing the previous one, ensuring constant data reception without reconnection. For Android, OkHttp WebSocket is used, which provides a similar interface with callbacks onOpen, onMessage, onClosing, and onClosed, as well as automatic reconnection upon connection loss.

When working with WebSocket in mobile applications, it is important to consider lifecycle management: when the app goes into the background, the connection may be terminated by the system. On iOS, the connection must be re-established upon returning to the foreground via the sceneDidBecomeActive delegate. On Android, Lifecycle-aware components or a Service should be used to maintain the connection. Additionally, it is recommended to implement exponential backoff for reconnection — increasing the interval between attempts from 1 to 30 seconds — to avoid creating excessive load on the server during temporary network issues.

Frequently Asked Questions

How does WebSocket differ from HTTP?

WebSocket establishes a persistent full-duplex connection where both sides can send data at any time. HTTP operates on a request-response scheme where each exchange requires a new connection and full headers. WebSocket uses a single TCP channel and headers of only 2-14 bytes, dramatically reducing latency.

What port does WebSocket use?

WebSocket uses port 80 for unsecured connections (ws://) and port 443 for secured ones (wss://). This allows it to pass through most proxy servers and corporate firewalls without additional configuration. Port 443 is recommended for production environments due to TLS encryption.

Is WebSocket supported in mobile applications?

Yes, WebSocket is supported on all mobile platforms. On iOS, the native URLSessionWebSocketTask class is available since iOS 13. On Android — the OkHttp WebSocket class and the standard java.net.WebSocket. For React Native, the react-native-websocket library exists.

What is WebSocket Secure (wss://)?

WebSocket Secure is the secured version of the protocol operating over TLS. All data is encrypted just like in HTTPS. WSS is mandatory for production applications, especially when transmitting authentication tokens or personal data over WebSocket.

What alternatives to WebSocket exist?

The main alternatives are: HTTP Long Polling (the server holds the request open), Server-Sent Events (unidirectional stream from the server), and WebRTC Data Channel (peer-to-peer communication). Server-Sent Events are simpler to implement but do not support sending from client to server.

Summary

  • WebSocket is a full-duplex real-time protocol operating over TCP and standardized as RFC 6455
  • Persistent connection eliminates HTTP handshake overhead, reducing latency to 1-5 ms
  • Frame header is only 2-14 bytes compared to 400-800 bytes in HTTP
  • Used in chats, online games, trading terminals, IoT, and collaborative editing
  • WSS provides TLS encryption and is recommended for production environments
  • The protocol is supported by all browsers, mobile platforms, and server languages
  • Use WebSocket for real-time features and HTTP for standard REST requests

We will develop a mobile application turnkey

IT Sectr creates iOS and Android applications for startups and businesses since 2017. We will advise you and propose the best solution.

Discuss the project

Read also