Real-Time Communication Without Limits

WebSockets:

Real-Time Communication Without Limits

DEVSHARE

Have you ever wondered how a server can notify a client that something has happened? Maybe you have but you thought that was impossible. Perhaps you have implemented something like http long polling. What if I told you that there was a better way? This article aims to convince you to consider implementing WebSockets in your next project.

websockets

WebSocket protocol general information

WebSockets protocol was first standardized in 2011 in RFC 6455. Its goal was to enable real-time two-way communication between client and server. Instead of the client constantly asking the server whether something happened, or opening a connection and keeping it open until the server responded, communication can now happen instantaneously and without the client having to initiate it every time. This reduces latency and bandwidth usage, as well as providing for an efficient and optimized way of bidirectional and server-initiated messaging.

The protocol itself resides on the 7th level of the OSI model, but depends on TCP on the 4th level by using a single TCP connection. It has its own URI scheme:

For unsecured connections:

ws://

For secure connections:

wss://

Protocol relies on HTTP during the creation of the connection (handshake process), and mostly uses its standard ports for connections. Even though it should not matter on which port server accepts WebSocket connections, it is recommended that it listens on either port 80 (unsecured connections), or 443 (secure connections), since sometimes other ports may be blocked.

Communication flow

The diagram shows the flow of communication between the client and the server.

Diagram of WebSocket real-time two-way communication between client and server

The client is the one that needs to initiate the creation of the connection (handshake) itself by sending a specific request. The server then needs to send a specific response, and, if all goes well, the connection gets opened (the details of the process will be explained in the next section). After that, bidirectional communication occurs, where each side can send data at will, until one of them initiates the closing handshake.

Protocol handshake

The process of creating the websocket connection is called a handshake. The handshake itself occurs via HTTP.

Handshake request

The client needs to send a regular HTTP request to the server. The request method needs to be GET and the version of the protocol needs to be at least 1.1. Hereby an example of such a request. Request and response examples are taken from the MDN documentation on how to write WebSocket servers.

GET /chat HTTP/1.1
Host: example.com:8000
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13

Client indicates that this request is supposed to create a websocket connection by sending Upgrade and Connection headers. The Upgrade header has the value websocket, and the Connection header has the value Upgrade. Two more headers that are specific for the protocol are sent as well: Sec-WebSocket-Key and Sec-WebSocket-Version. They will be explained in the handshake response section.

Handshake response

Server needs to respond to the handshake request. Below is an example of the response.

HTTP/1.1 101 Switching Protocols​
Upgrade: websocket​
Connection: Upgrade​
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=​

Server needs to respond with the status code 101 Switching protocols. Responding with any other status would mean that the handshake has failed. The response also has Connection and Upgrade headers with the same values they had in the request. If the server supports WebSocket and can handle subsequent requests as WebSocket requests, it responds with the Sec-Websocket-Accept header.

Value in the Sec-WebSocket-Accept header is calculated based on the value sent in the request’s Sec-WebSocket-Key header. A so-called “magic string” (with the value of 258EAFA5-E914-47DA-95CA-C5AB0DC85B11, which is defined in the WebSocket protocol specification) is concatenated to the value found in the Sec-WebSocket-Key header. That concatenated string is then hashed using the SHA-1 algorithm, and converted to base64 format. That final value is what is sent in the Sec-WebSocket-Accept header.

Another header that is sent in the request is Sec-WebSocket-Version. It states the version of the WebSocket protocol that the client expects. If the server does not support that version, it should add a Sec-WebSocket-Version header in the response, in which it states which version it does support.

WebSocket extensions and subprotocols

Additional headers that can be included in the request are Sec-WebSocket-Extensions and Sec-WebSocket-Protocol. They are optional, but if included, have significant importance. Protocols define the structure of the payload (think of it like a schema) and extensions add additional features to the protocol (for example compressing the message). The values these headers can have are defined by IANA (Internet Assigned Numbers Authority), which maintains a complete list that can be found here.

The client can send either a comma-separated list of subprotocols that it wants, or add a separate Sec-WebSocket-Protocol header for each subprotocol. The server chooses the first one it supports and sends it in the response.

websockets

WebSocket use cases

WebSocket protocol can be used in a variety of cases.

Server notifications

For example, if a client initiates a task on the server that takes some time to finish, it can use a websocket connection to be notified when that action completes.

Multiplayer games

Many players are connected to the same server in order to play a game, and the server performs calculations and updates the game state when necessary. For players to be aware of all updates, the server needs to broadcast them and WebSocket protocol is sometimes used for this kind of scenario.

Real-time messaging applications

Ideally, when you receive a message, you want to be notified instantly and not have any delay. WebSocket protocol can help with that, so that when a server receives a message, it is forwarded to you instantaneously.

Collaborative editing

Similarly to gaming, when multiple people are editing the same document at once, they all want to be aware of all updates the moment they happen, otherwise the document may end up in an inconsistent state.

Conclusion

WebSockets revolutionized the Internet, by introducing a more straightforward approach to two-way communication. Compatibility with HTTP, the de facto and de jure standard communication protocol on the web, makes it even more appealing. Even though it is relatively new, it is here to stay, and will without a doubt shape the future of internet communication. See you on our blog on the next topic.

Dimitrije Karanfilović

ELEVATE
YOUR
CLOUD.

I am looking for help with...
How did you hear about us?