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讲起来太多了,之后再说吧。)


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