項目中以前已經使用過 websocket 進行一些和服務器的實時數據通訊,可是對於協議自己並不十分了解,也是藉此機會學習一下並分享出來。html
應用層,和 Http 協議是同級關係java
既然同 Http 協議是同層,爲何還須要另外一個協議?它有什麼好處?git
答案很簡單,由於 HTTP 協議的設計之初就是:通訊只能由客戶端發起。 舉例來講,咱們想了解當前的股票價格,只能是客戶端向服務器發出請求,服務器返回查詢結果。要想實時刷新股票的價格,這個 HTTP 協議搞起來就有點費勁了,由於 HTTP 協議作不到服務器主動向客戶端推送信息。github
這種單向請求的特色,註定了若是服務器有連續的狀態變化,客戶端要獲知就很是麻煩。有沒有什麼辦法能夠解決雙向通訊的問題呢?web
輪詢是在特定的的時間間隔(如每1秒),由瀏覽器對服務器發出HTTP請求,而後由服務器返回最新的數據給客戶端的瀏覽器。這種傳統的模式帶來很明顯的缺點,即瀏覽器須要不斷的向服務器發出請求,然而HTTP請求可能包含較長的 頭部 ,其中真正有效的數據可能只是很小的一部分,顯然這樣會浪費不少的帶寬等資源。瀏覽器
Comet is a web application model in which a long-held HTTPS request allows a web server to push data to a browser, without the browser explicitly requesting it.安全
Comet is an umbrella term, encompassing multiple techniques for achieving this interaction. All these methods rely on features included by default in browsers, such as JavaScript, rather than on non-default plugins.bash
The term Comet is not an acronym, but was coined by Alex Russell in his 2006 blog post Comet: Low Latency Data for the Browser.服務器
阻塞模型:客戶端發送一個超時時間很長的 Request,服務器 hold 住這個鏈接,在有新數據到達時返回Response,相比頻繁輪詢,佔用的網絡帶寬少了。websocket
上述的 問題 在於對於網絡帶寬的佔用及服務器的資源的開銷。
輪詢的效率低,很是浪費資源(由於必須不停鏈接,或者 HTTP 鏈接始終打開) 長輪詢須要服務器一直 hold 住連接直到有數據返回,實際上是服務端的一種 hack 方案。
因而,WebSocket 就這樣出現來解決上述問題的。
WebSocket 協議在2008年誕生,2011年成爲國際標準。全部瀏覽器都已經支持了。能夠在這裏查看各個瀏覽器的支持狀況。
WebSocket 是一種在單個 TCP 鏈接上進行 全雙工 通訊的協議。
其餘特色包括:
ws://example-host.com:80/path
// WebSocket + TLS
wss://example-host.com:443/path
複製代碼
The WebSocket connection must be an HTTP/1.1 GET request, and include the following headers:
Host
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key
Sec-WebSocket-Version
If any of these are not included in the HTTP headers, the server should respond with an HTTP error code 400 Bad Request.
GET ws://localhost:8181/ HTTP/1.1
Origin: http://localhost:8181
Host: localhost:8181
Sec-WebSocket-Key: zy6Dy9mSAIM7GJZNf9rI1A==
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Version: 13
複製代碼
Upon receiving a valid upgrade request with all required fields, the server will decide on the accepted protocol, and any extensions, and send back an HTTP response with status code 101 along with the Sec-WebSocket-Accept handshake acknowledgment.
HTTP/1.1 101 Switching Protocols
Connection: Upgrade
Sec-WebSocket-Accept: EDJa7WCAQQzMCYNJM42Syuo9SqQ=
Upgrade: websocket
WebSocket Frame
複製代碼
更多詳情請參閱 RFC 6445
《WebSocket: Lightweight Client-Server Communications》 www.ruanyifeng.com/blog/2017/0… baike.baidu.com/item/WebSoc… www.ibm.com/developerwo…