Understanding WebSocket Protocol

1. Understanding Protocol Basics

WebSocket (RFC 6455) is a full-duplex, bidirectional TCP-based protocol over a single long-lived connection, initiated by an HTTP/1.1 Upgrade handshake. Schemes: ws:// (port 80) and wss:// (port 443, TLS).

PropertyValueDescription
RFC6455Core protocol specification
TransportTCPPersistent single connection
DirectionFull-duplexBoth peers send anytime
Schemesws, wssPlain / TLS-encrypted
Default Ports80 / 443HTTP / HTTPS aligned
FramingBinary framesText (UTF-8) or binary payloads
Max Frame2^63 bytes64-bit extended length
Sub-protocolSec-WebSocket-ProtocolApplication-level protocol

2. Understanding Handshake Process

HeaderDirectionPurpose
Upgrade: websocketClientRequest protocol switch
Connection: UpgradeClientSignal upgrade intent
Sec-WebSocket-KeyClientRandom 16-byte base64 nonce
Sec-WebSocket-Version: 13ClientProtocol version
Sec-WebSocket-ProtocolBothSubprotocol negotiation
Sec-WebSocket-ExtensionsBothExtension negotiation (e.g. permessage-deflate)
Sec-WebSocket-AcceptServerSHA-1(key + GUID) base64
101 Switching ProtocolsServerHandshake success status

Example: Raw Handshake

GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Sec-WebSocket-Protocol: chat.v2
Origin: https://app.example.com

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Sec-WebSocket-Protocol: chat.v2

3. Understanding Frame Structure

FieldBitsDescription
FIN1Final fragment flag
RSV1-33Reserved (used by extensions)
Opcode40x0 cont, 0x1 text, 0x2 binary, 0x8 close, 0x9 ping, 0xA pong
MASK11 for client→server (required)
Payload len7 / 7+16 / 7+64Length encoding
Masking-key0 / 32XOR key when MASK=1
PayloadvariableApplication data

4. Understanding Connection States

ConstantValueMeaning
CONNECTING0Handshake in progress
OPEN1Ready to send/receive
CLOSING2Close frame sent, awaiting response
CLOSED3Underlying TCP closed

5. Comparing WebSocket vs HTTP

AspectWebSocketHTTP/1.1
DirectionBidirectionalClient → Server
ConnectionPersistentRequest/response
Overhead2-14 bytes/frame~500+ bytes/header
LatencyLow (no handshake per msg)Higher
CachingNoYes
Use CaseRealtimeDocument/API fetch

6. Comparing WebSocket vs SSE

FeatureWebSocketSSE
DirectionBidirectionalServer → Client only
Protocolws/wss (TCP)HTTP
BinaryNativeText only (base64 workaround)
Auto-reconnectManualBuilt-in
Proxy supportMay require configWorks through any HTTP proxy
Max connectionsHighLimited per origin (HTTP/1.1: ~6)

7. Comparing WebSocket vs Long Polling

AspectWebSocketLong Polling
Connections1 persistentRepeated HTTP
Latency~msNetwork RTT per msg
Server loadLowHigh (connection churn)
Header overheadMinimalFull headers each request
ImplementationNative APITrivial fallback

8. Understanding Use Cases

Use CaseWhy WebSocket
Chat / MessagingBidirectional, low latency
Live trading / quotesSub-second updates, server push
Multiplayer gamesLow overhead, binary frames
Collaborative editingCRDT/OT delta sync
IoT telemetryPersistent device→server channel
Live dashboardsServer-initiated updates
WebRTC signalingOut-of-band SDP/ICE exchange

9. Understanding Protocol Limitations

LimitationDetail
No request/responseMust be modeled at app level
No HTTP semanticsNo caching, no status codes per msg
No multiplexingOne logical channel per connection (HTTP/2 push N/A)
StatefulHard to scale horizontally without sticky sessions/pub-sub
Proxy traversalSome intermediaries strip Upgrade headers
ReconnectionManual logic required

10. Understanding Browser Support

FeatureSupportNotes
WebSocket APIAll BrowsersChrome 16+, FF 11+, Safari 7+, Edge 12+
Binary (ArrayBuffer/Blob)All BrowsersSet binaryType
permessage-deflateModern BrowsersNegotiated; Safari has quirks
WebSocketStream EXPERIMENTALExperimentalChrome behind flag
Workers/Service WorkersAll BrowsersService Workers cannot hold open WS