WebSockets
WebSockets is a modern web technology that enables a persistent, full-duplex (two-way) communication channel between a client and a server.
Unlike normal HTTP requests, WebSocket connections allow messages to be sent from the client to the server and vice versa, at any time over the same single TCP connection, which is kept open for as long as needed.
To start the protocol, an initial handshake is done in the form of an HTTP request and response, as WebSockets was designed to be compatible with HTTP servers, allowing a backend to handle both normal HTTP requests and WebSockets.
The client request in the websockets handshake has the following form:
GET /socket HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: kakflkJDO2K24ZQ==
Origin: http://example.com
Sec-WebSocket-Protocol: chat
Sec-WebSocket-Version: 13
On the other hand, the server response looks like:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMe2lpw1281dkajeo=
Sec-WebSocket-Protocol: chat
After that, the server indicates that it accepts the WebSocket connection, and the communication is established. The messages exchanged are of different types such as plain text, binary data or control messages.
Finally, when one of the sides sends a close message, the underlying TCP connections are closed, and the communication is finished.
WebSockets vs XMLHttpRequest
When using traditional web methods like XMLHttpRequest (as in AJAX), every message sent opens a new connection, or at least a new request/response cycle, which can add delay and overhead.
With WebSockets, the same open connection is reused, so data can flow rapidly back and forth without repeatedly reconnecting or waiting for each response before sending the next request.
This makes WebSockets ideal for real-time applications such as chats, live sports, online games, financial tickers, or collaborative editing, where quick updates from server to client are crucial.
Last updated