本文轉(zhuǎn)自我的博文HTTP/2 和 Websocket
HTTP/2 是什么
這篇文章講的比較詳細(xì):
它是 google 提出的開源協(xié)議岂嗓,旨在提高網(wǎng)絡(luò)傳輸效率
它是二進(jìn)制協(xié)議
它采用多路復(fù)用解決 HTTP 1.1 的 head-of-line blocking (HOL Blocking)問題(較慢的請求阻塞其它請求的問題)
它通過壓縮 http 頭提高效率
它支持全雙工,因此可以使用 Server Push 推送到客戶端
與 websocket 的比較
HTTP/2 | WebSocket | |
---|---|---|
Headers 頭 | Compressed (HPACK) 請求頭部壓縮 | None 無 |
Binary 二進(jìn)制 | Yes | Binary or Textual 二進(jìn)制或文本都支持 |
Multiplexing 多路復(fù)用 | Yes | Yes |
Prioritization 優(yōu)先化 | Yes | No |
Compression 壓縮 | Yes | Yes |
Direction 方向 | Client/Server + Server Push (Server Push只能瀏覽器消化榕订,不支持API,也就是代碼無法使用) | Bidirectional 雙向 |
Full-duplex 全雙工 | Yes | Yes |
問題
- HTTP/2 Server Push 不能被代碼使用阱表,所以還得配合SSE(Server sent event),無論從coder還是運維的角度來看,這混搭增加了復(fù)雜度篙耗。
- IE對http2以及SSE都支持的不好
- HTTP/2 連接不確定性會永遠(yuǎn)保持連接劳吠,而websocket有onclose事件引润,對代碼友好
HTTP/2 Servers are encouraged to maintain open connections for as long as possible but are permitted to terminate idle connections if necessary. When either endpoint chooses to close the transport-layer TCP connection, the terminating endpoint SHOULD first send a GOAWAY (Section 6.8) frame so that both endpoints can reliably determine whether previously sent frames have been processed and gracefully complete or terminate any necessary remaining tasks.
- 多個tab頁windows頁可能共用一個HTTP/2連接,你無法知道Server Push來自哪一個
- 由于多路復(fù)用痒玩,以前基于HTTP 1.1的網(wǎng)站提速技巧Domain sharding(由于瀏覽器限制同一域名最多連接數(shù))將不再起作用淳附。
實際實現(xiàn)狀態(tài)
HTTP2 vs Websocket
顯而易見,http2 在瀏覽器服務(wù)器上限制頗多蠢古,而 websocket 基本普及奴曙。
再來看看SSE, 支持程度仍然不如websocket。
結(jié)論:
HTTP/2 完全不能替代websocket草讶,各有各的適用場景洽糟。我個人偏好,做app還是偏向于websocket堕战,參看我的另外一博文介紹Meteor.