最後更新: 2019-10-10
socket.io
real-time bidirectional event-based communication, it relies on Engine.IO
Socket.IO is not a WebSocket implementation.
(它是用 Long Polling 的, WebSocket as a transport when possible)
i.e.
wss://URL/socket.io/?version=95&lastupdate=Epoch&EIO=3&transport=websocket&sid=XXXXXXXXXXXXX
Connections are established even in the presence of
- proxies and
- load balancers
* sticky-session requirement
封裝了多種協議(Comet: iframe, long polling ...), 蔽了所有底層細節
設計
- Binary streaming (image, audio, video)
- Multiplexing support
Socket.IO allows you to create several Namespaces,
which will act as separate communication channels but will share the same underlying connection.
- Room support
Within each Namespace, you can define arbitrary channels, called Rooms,
that sockets can join and leave. (用圖: to send notifications to a group of users)
- Auto-reconnection support
- Disconnection detection(heartbeat mechanism)
Comet
彗星
把發出的 Request 像彗星的尾巴一樣拉的很長, 讓伺服器保持連線的狀態, 持續讓 Server 端 Response 資料回來
Long Polling
* It works on every platform, browser or device
* non-blocking IO
Client 向 Server 發出請求, Server 接收到請求後,
server 並不一定立即發送回應給 client, 而是看數據是否更新,
如果數據已經更新了的話, 那就立即斷掉 client,
接著 Client 觸發新一個的 Request. (新的數據更新)
但如果數據沒有更新, 那就把這個請求保持住(不回應).
如果 server 的數據長時間沒有更新, 一段時間後,請求便會超時,
client 收到超時信息後, 再發送一個新的請求給 server 建立連線.