Web Sockets

I want to read about web sockets.

Date Created:
2 460

References



Related


  • Transmission Control Protocol
    • The Transmission Control Protocol (TCP) is one of the main protocols of the Internet protocol suite. It originated in the initial network implementation in which it complemented the Internet protocol. TCP provides reliable, ordered, and error-checked delivery of a stream of octets (bytes) between applications running on hosts communicating via an IP network. Major internet applications such as the World Wide Web, email, remote administration, and file transfer rely on TCP, which is part of the Transport layer of the TCP/IP suite.
    • TCP is connection-oriented, meaning that sender and receiver firstly need to establish a connection based on agreed parameters; they do this through three-way handshake procedure. The server must be listening (passive open) for connection requests from clients before a connection is established.
  • IETF
    • The Internet Engineering Task Force (IETF) is a standards organization for the Internet and is responsible for the technical standards that make up the Internet protocol suite. It has no formal membership roster or requirements and all its participants are volunteers. Their work is usually funded by employers or other sponsors. Ot was initially supported by the Federal Government.

IETF

  • handshake
    • In computing, a handshake is a signal between two devices or programs, used to , e.g. authenticate, coordinate. An example is the handshaking between a hypervisor and an application in a guest virtual machine.
    • In telecommunications, a handshake is an automated process of negotiation between two participants through the exchange of information that establishes the protocols of a communication link at the start of the communication, before full communication begins. The handshaking process usually takes place in order to establish rules for communication when a computer attempts to communicate with another device. Signals are usually exchanged in order to establish communication rules between two devices to establish a communication link.
  • Upgrade header
    • The Upgrade header field is an HTTP header field introduced in HTTP/1.1. In the exchange, the client begins by making a cleartext request, which is later upgraded to a newer HTTP protocol version or switched to a different protocol. A connection upgrade must be requested by the client; if the server wants to enforce an upgrade it may send a 426 Upgrade Required response.
      • In cryptography, plaintext (cleartext) usually means unencrypted information pending input into cryptographic algorithms, usually encryption algorithms. This usually refers to data that is transmitted or stored unencrypted.
  • Duplex
    • A duplex communication system is a point-to-point system composed of two or more connected parties or devices that can communicate with one another in both directions. Duplex systems are employed in many communications networks, wither to allow for simultaneous communication in both directions between two connected parties or to provide a reverse path for the monitoring and remote adjustment of equipment in the field.
  • Polling
    • Polling, or interrogation, refers to actively sampling the status of an external device by a client program as a synchronous activity. Polling is most often used in terms of input/output, and is often referred to as polled I/O or software-driven I/O. A good example of hardware implementation is a watchdog tier.
  • Same-origin Policy
    • In computing, the same-origin policy (SOP) is a concept in the web-app application security model. Under the policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin. An origin is defined as a combination of URI scheme, host name, and port number. This policy prevents a malicious script on one page from obtaining access to sensitive data on another web page through that page's DOM.


Notes


WebSocket is a computer communications protocol, providing a simultaneous two-way communication channel over a single Transmission Control Protocol (TCP) connection. The WebSocket protocol was standardized by the IETF as RFC 6455 in 2011. The current specification allowing web applications to use this protocol is known as WebSockets. It is a living standard maintained by the WHATWG and a successor to the WebSocket API from the W3C.

WebSocket is distinct form HTTP used to serve most webpages. Although they are different, RFC 6455 states that WebSocket is designed to work over HTTP ports 443 and 80 as well as to support HTTP proxies and intermediaries. To achieve compatibility with HTTP, the WebSocket handshake uses the HTTP Upgrade header to change from the HTTP protocol to the WebSocket protocol.

Difference Between WebSocket and HTTP

The WebSocket protocol enables full-duplex interaction between a web browser (or other client application) and a web server with lower overhead than half-duplex alternatives such as HTTP polling, facilitating real-time data transfer from and to the server. This is made possible by providing a standardized way for the server to send content to the client without being first requested by the client, allowing messages to be passed back and forth while keeping the connection open. In this way, a two-way ongoing conversation can take place between the client and the server. The communications are usually done over TCP port 443, which is beneficial for environments that block non-web Internet connections using a firewall. Additionally, WebSocket enables streams of messages on top of TCP. TCP alone deals with streams of bytes with no inherent concept of a message.

The WebSocket protocol specification defines ws (WebSocket) and wss (WebSocket Secure) as two new uniform resource identifier (URI) schemes that are used for unencrypted and encrypted connections respectively.

Client Example

// Connect to server
ws = new WebSocket("ws://127.0.0.1/scoreboard") // Local server
// ws = new WebSocket("wss://game.example.com/scoreboard") // Remote server

ws.onopen = () => {
console.log("Connection opened")
ws.send("Hi server, please send me the score of yesterday's game")
}

ws.onmessage = (event) => {
console.log("Data received", event.data)
ws.close() // We got the score so we don't need the connection anymore
}

ws.onclose = (event) => {
console.log("Connection closed", event.code, event.reason, event.wasClean)
}

ws.onerror = () => {
console.log("Connection closed due to error")
}


Server Example

from socket import socket
from base64 import b64encode
from hashlib import sha1

MAGIC = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"

# Create socket and listen at port 80
ws = socket()
ws.bind(("", 80))
ws.listen()
conn, addr = ws.accept()

# Parse request
for line in conn.recv(4096).split(b"\r\n"):
if line.startswith(b"Sec-WebSocket-Key"):
nonce = line.split(b":")[1].strip()

# Format response
response = f"""\
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: {b64encode(sha1(nonce + MAGIC).digest()).decode()}

"""

conn.send(response.replace("\n", "\r\n").encode())

while True: # decode messages from the client
header = conn.recv(2)
FIN = bool(header[0] & 0x80) # bit 0
assert FIN == 1, "We only support unfragmented messages"
opcode = header[0] & 0xf # bits 4-7
assert opcode == 1 or opcode == 2, "We only support data messages"
masked = bool(header[1] & 0x80) # bit 8
assert masked, "The client must mask all frames"
payload_size = header[1] & 0x7f # bits 9-15
assert payload_size <= 125, "We only support small messages"
masking_key = conn.recv(4)
payload = bytearray(conn.recv(payload_size))
for i in range(payload_size):
payload[i] = payload[i] ^ masking_key[i % 4]
print(payload)

Protocol

Steps:

  1. Opening handshake (HTTP request + HTTP response) to establish a connection
  2. Data messages to transfer application data
  3. Closing handshake (two Close frames) to close the connection

Opening Handshake

The client sends an HTTP request (method GET_ and the server returns an HTTP response with status code 101 (Switching Protocols) on success. This means a WebSocket server can use the same port as HTTP and HTTPS because the handshake is compatible with HTTP.

Example Request:

GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin: http://example.com

Example Response

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat

Once the connection is established, communication switches to a binary frame-based protocol which does not conform to the HTTP Protocol. SEC-WebSocket-Key and Sec-WebSocket-Accept are intended to prevent a caching proxy from re-sending a previous WebSocket conversation, and does not provide any authentication, privacy, or integrity.

Frame-Based Messages

After the opening handshake, the client and server can, at a any time, send message to each other, such as data messages (text or binary) and control messages (close, ping, pong). A message is composed of one or more frames.

Fragmentation allows a message to be split into two or more frames. It enables sending messages with initial data available but complete length unknown. Without fragmentation, the whole message must be sent in one frame, so the complete length is needed before the first byte can be sent, which requires a buffer.

Server Implementations

  • Nginx has supported WebSockets since 2013, implemented in version 1.3.13, including acting as a reverse proxying and load balancer of WebSocket applications.

Security Considerations

Unlike regular cross-domain HTTP requests, WebSocket requests are not restricted by the same-origin policy. Therefore, WebSocket servers must validate the Origin header against expected origins during connection establishment, to avoid cross-site WebSocket hijacking attacks, which might be possible when the connection is authenticated with cookies or HTTP authentication. It is better to use tokens or similar protection mechanisms to authenticate the WebSocket connection when sensitive (private) data is being transferred over the WebSocket.


Comments

You have to be logged in to add a comment

User Comments

Insert Math Markup

ESC
About Inserting Math Content
Display Style:

Embed News Content

ESC
About Embedding News Content

Embed Youtube Video

ESC
Embedding Youtube Videos

Embed TikTok Video

ESC
Embedding TikTok Videos

Embed X Post

ESC
Embedding X Posts

Embed Instagram Post

ESC
Embedding Instagram Posts

Insert Details Element

ESC

Example Output:

Summary Title
You will be able to insert content here after confirming the title of the <details> element.

Insert Table

ESC
Customization
Align:
Preview:

Insert Horizontal Rule

#000000

Preview:


View Content At Different Sizes

ESC

Edit Style of Block Nodes

ESC

Edit the background color, default text color, margin, padding, and border of block nodes. Editable block nodes include paragraphs, headers, and lists.

#ffffff
#000000

Edit Selected Cells

Change the background color, vertical align, and borders of the cells in the current selection.

#ffffff
Vertical Align:
Border
#000000
Border Style:

Edit Table

ESC
Customization:
Align:

Upload Lexical State

ESC

Upload a .lexical file. If the file type matches the type of the current editor, then a preview will be shown below the file input.

Upload 3D Object

ESC

Upload Jupyter Notebook

ESC

Upload a Jupyter notebook and embed the resulting HTML in the text editor.

Insert Custom HTML

ESC

Edit Image Background Color

ESC
#ffffff

Insert Columns Layout

ESC
Column Type:

Select Code Language

ESC
Select Coding Language

Insert Chart

ESC

Use the search box below

Upload Previous Version of Article State

ESC