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
-
HTTP handshake
-
Client sends
Upgrade: Websocket
:include the following in the HTTP header:
1GET /chat HTTP/1.12Host: example.com:80003Upgrade: websocket // Request to upgrade HTTP conn to WebSocket conn4Connection: Upgrade // Request to upgrade conn (must accompany the `Upgrade` header)5Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== // A nonce that protects against unauthorized upgrade6Sec-WebSocket-Version: 13 // 13 is the only accepted version -
Server responds
101 Switching Protocols
:1HTTP/1.1 101 Switching Protocols // Comfirm the upgrade2Upgrade: websocket // Comfirm switch to WebSocket3Connection: Upgrade4Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=5// Sec-WebSocket-Accept: A hashed and base64-encoded string derived6// from the client's Sec-WebSocket-Key to verify the handshake -
Communicate messages in WebSocket format