eolas/zk/Web_sockets.md

52 lines
2.5 KiB
Markdown

---
tags: [networks, network-protocols, WebSocket]
created: Monday, April 14, 2025
---
# Web sockets
The WebSocket protocol provides a mechanism whereby data can continuously be
shared between a client and a server in both directions.
This contrasts with standard HTTP whereby a server can only send data when a
client specifically requests it and the communication channel is closed until
such a request is made.
Whereas HTTP works on the basis of a client-server architecture, WebSocket is an
event-driven architecture. Under an event-driven architecture, _events_ trigger
data flows rather than client requests.
Examples of its application include instant messaging platforms where messages
are sent in real time, stock trading platforms, social media feeds and
cloud-based collaboration tools (e.g. Google Sheets). Hence WebSocket is best
suited to applications where the immediacy and concurrency of server resolution
is a factor.
WebSocket was borne out of the limitations of HTTP. Prior to the creation of the
WebSocket protocol, event-driven communication was attempted over HTTP through
"long polling". Basically, the server sends a request to the server and if the
response is not available, the server holds the request until the response is
available and then returns it. Then, after an interval, the client sends the
same request again and the process repeats. This is obviously inefficient.
WebSocket is an [Application Layer](./Application_Layer_of_Internet_Protocol.md)
protocol just like HTTP. HTTP is used as the initial connection mechanism but
the resulting TCP connection is kept alive after the HTTP request completes,
establishing the web socket. The standard HTTP handshake takes place but the
HTTP request will include an 'Upgrade' header that indicates the client wants to
establish a socket. The presence of this header results in the protocol being
upgraded from HTTP to WebSocket.
> This is possible because both HTTP and WebSocket are Application Layer
> protocols that run on top of the same TCP connection.
## Encryption
In the case of moving from HTTPS to WebSocket, the encryption of the former
protocol is maintained. Although there is a protocol switch, the data is still
being transferred on the same 443 port (used for HTTPS). Although the protocol
has changed at the Application Layer, the encryption established at the TCP
Layer is still in place.
The HTTPS analog for WebSocket is WebSocketSecure (WSS). Thus HTTPS/WSS is the
secure version of the HTTP/WS protocols.