C.W.K.
Stream
Lesson 05 of 08 · published

Enter WebSocket: Full Duplex

~14 min · foundations, websocket, handshake

Level 0Poller
0 XP0/60 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

True bidirectional, persistent

WebSocket is what you reach for when both sides need to send messages frequently and asynchronously. Once the connection is established, either end can write at any moment. There is no concept of a "request" or "response" — there are just frames flowing in both directions over a single TCP connection that stays open until somebody closes it.

The upgrade handshake

WebSocket starts life as an HTTP/1.1 GET with special headers. The server responds with 101 Switching Protocols and the same socket stops speaking HTTP. From that moment on, the bytes on the wire are WebSocket frames defined by RFC 6455.

ws:// vs wss://

ws:// is unencrypted (port 80 by default), wss:// is TLS-wrapped (port 443). In production you use wss:// always. Many proxies and corporate firewalls outright drop unencrypted WebSocket. Even ignoring policy, you do not want chat or auth tokens crossing the wire in cleartext.

Code

What an upgrade looks like on the wire·http
# Client request
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Origin: https://example.com

# Server response (handshake accepted)
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Round-trip in WebSocket land·text
Client                          Server
  |                                |
  |---- HTTP Upgrade Request ----->|
  |<--- 101 Switching Protocols ---|
  |                                |
  |======= WebSocket OPEN =========|
  |                                |
  |---- "hello" ------------------>|
  |<--- "hi there" ----------------|
  |<--- "news update" -------------|   server pushes anytime
  |---- "typing..." -------------->|   client pushes anytime
  |<--- "user joined" -------------|
  |---- close 1000 -------------->|
  |<--- close 1000 ----------------|
  |======= CLOSED =================|

External links

Exercise

Open https://websocket.org/tools/websocket-echo-server/ (or run any echo server you trust). Open the network panel, watch the WebSocket upgrade. Find the request, expand it, locate Sec-WebSocket-Key in the request and Sec-WebSocket-Accept in the response. You will compute the relationship between them in the next lesson.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.