webSocket整理(待續)-2020-08-09

1.什麼是webSocket

wiki/WebSocket
webSocke是一種網絡長連接協議,基於tcp的一種應用層協議。客戶端與服務器連接還是使用http協議的連接,並且端口也依舊使用http的端口,ws使用的時443端口,wss則是使用80端口。雖然是兩種不同的協議,但是webSocket的實現是在http實現的基礎上改進的。

2. webSocket的優勢,適用場景(對比HTTP)

與HTTP對比:websocket可以實現服務器主動發送信息到客戶端。相對於http使用ajax輪詢(間隔一定時間發送一次請求)或者long poll(沒有處理完就不響應),更加高效(http每次發送請求都需要校驗頭部,而且是無狀態連接,websocket連接之後則不需要再校驗http頭部,則效率更高。)

  • HTTP還是一個無狀態協議。請求之間數據不共享,需要的話只能重新發送。
  • HTTP只能被動response,服務器不能主動發送請求到客戶端
  • Http1.1 的 keep-alive雖然看起來像是長連接,實際上是將多個http請求合併成一個(一個http請求發送多個request和接受多個response ),request和respond請求相等,而且服務器不能主動向客戶端發送請求。

在spring的websocket文檔中,websocket一般用於頻率高,傳輸數據大,需要及時響應(實時性高)的場景。

2.1 HTTP和WebSocket請求頭的區別

Protocol_upgrade MDN參考

  • http connection狀態爲close:因爲http也是基於TCP傳輸,所以也是用進行連接的。只是HTTP是無狀態,並且一次請求對應一次響應,所以只要有響應,或者響應超時,一次信息http請求過程就算結束了,所以連接就直接釋放了,有新的http請求就需要有重新建立連接了。
留下疑問:如果webSocket斷開連接是不是也會斷開connection:close,還是繼續爲Upgrade
  • webSocket主要是通過將request 的connection:+Upgrade並且添加(Upgrade:websocket)(升級爲websocket)來區別。返回狀態碼爲101,表示切換協議,接受轉換爲websocket,如果不接受,則返回例如426的狀態碼

If the server can't communicate using the specified version of the WebSocket protocol, it will respond with an error (such as 426 Upgrade Required)

  • Sec-WebSocket-Key通過base64生成,只是爲了防止濫用,或者錯誤連接到不想使用webSocket的地方,好像並沒有提及可以用該字段來區別哪個連接。(曾經的疑問:能通過該key 判斷應該推送到哪個用戶?)

    Provides information to the server which is needed in order to confirm that the client is entitled to request an upgrade to WebSocket. This header can be used when insecure (HTTP) clients wish to upgrade, in order to offer some degree of protection against abuse. The value of the key is computed using an algorithm defined in the WebSocket specification, so this does not provide security. Instead, it helps to prevent non-WebSocket clients from inadvertently, or through misuse, requesting a WebSocket connection. In essence, then, this key simply confirms that "Yes, I really mean to open a WebSocket connection."
    向服務器提供所需的信息,以確認客戶端有權請求升級到WebSocket。 當不安全的(HTTP)客戶端希望升級時,可以使用此標頭,以提供一定程度的保護以防止濫用。 密鑰的值是使用WebSocket規範中定義的算法計算的,因此不提供安全性。 相反,它有助於防止非WebSocket客戶端無意間或由於濫用而請求WebSocket連接。 因此,從本質上講,該密鑰只​​是確認“是的,我的意思是打開WebSocket連接”。

  • responsed的Sec-WebSocket-Accept :則是經過服務器確認,並且加密過後的 Sec-WebSocket-Key。一般會在握手完成出現,並且只會出現一次。(所以好像並沒有說該hash的作用)

    It will appear no more than once in the repsonse headers.
    它將在響應標題中出現不超過一次。

    If a Sec-WebSocket-Key header was provided, the value of this header is computed by taking the value of the key, concatenating the string "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" to it, taking the SHA-1 hash of that concatenated string, resulting in a 20-byte value. That value is then base64 encoded to obtain the value of this property.

  • webSocket與TCP協議
    webSocket連接過程打印出來如下圖所示。因爲webSocket基於TCP協議,所以不禁讓人懷疑這是不是TCP協議的三次握手。(TCP講起來太多了,之後再說吧。)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章