Jida's Blog

WebSockets

17th November 2024
Computer Network
WebSockets
Application Layer
Last updated:25th January 2025
2 Minutes
203 Words

1. WebSockets

If you’ve already know WebSockets, feel free to skip this part

1.1 Intro

1) what is WebSockets

  • Which layer: in Application Layer, just like HTTP
  • TCP-based: WebSockets work on a TCP connection → can play with TCP connection properties to reduce latency
  • Define: provide a full duplex communication channel over a single TCP connection

  • Full duplex:
    • Simultaneous communication: can send messages between each others at the same time
    • Single persistent connection: no need to establish a new connection for every messages once connection established
    • Low latency
    • Real-time interaction

2) use case

Ideal for applications requiring real-time data update:

  • Live chatting
  • Video game
  • Collaborative editing

3) URI schema

ws: or wss: for a secure WebSocket

1.2 How it works

1) establish WebSocket connection

  1. HTTP handshake

  2. Client sends Upgrade: Websocket:

    include the following in the HTTP header:

    1
    GET /chat HTTP/1.1
    2
    Host: example.com:8000
    3
    Upgrade: websocket // Request to upgrade HTTP conn to WebSocket conn
    4
    Connection: Upgrade // Request to upgrade conn (must accompany the `Upgrade` header)
    5
    Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== // A nonce that protects against unauthorized upgrade
    6
    Sec-WebSocket-Version: 13 // 13 is the only accepted version
  3. Server responds 101 Switching Protocols:

    1
    HTTP/1.1 101 Switching Protocols // Comfirm the upgrade
    2
    Upgrade: websocket // Comfirm switch to WebSocket
    3
    Connection: Upgrade
    4
    Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
    5
    // Sec-WebSocket-Accept: A hashed and base64-encoded string derived
    6
    // from the client's Sec-WebSocket-Key to verify the handshake
  4. Communicate messages in WebSocket format

Article title:WebSockets
Article author:Jida-Li
Release time:17th November 2024