简介
WebSocket 协定在2008年诞生,2011年成为国际标准。所有浏览器都曾经反对了。
它的最大特点就是,服务器能够被动向客户端推送信息,客户端也能够被动向服务器发送信息,是真正的双向平等对话,属于服务器推送技术的一种。
其余特点包含:
(1)建设在 TCP 协定之上,服务器端的实现比拟容易。
(2)与 HTTP 协定有着良好的兼容性。默认端口也是80和443,并且握手阶段采纳 HTTP 协定,因而握手时不容易屏蔽,能通过各种 HTTP 代理服务器。
(3)数据格式比拟轻量,性能开销小,通信高效。
(4)能够发送文本,也能够发送二进制数据。
(5)没有同源限度,客户端能够与任意服务器通信。
(6)协定标识符是ws(如果加密,则为wss),服务器网址就是 URL。
readyState
Constant | Value | Description |
---|---|---|
CONNECTING | 0 | The connection is not yet open. |
OPEN | 1 | The connection is open and ready to communicate. |
CLOSING | 2 | The connection is in the process of closing. |
CLOSED | 3 | The connection is closed. |
坑点: websocket.readyState ===3 这里 没有走 close 的生命周期
断线重连解决方案
- 在websocket/ws 这个框架中,会有open,message,close 和 error生命周期。
-
能够在 close 的生命周期中,执行reconnect流程参考最高赞答案.而后在error的生命周期中 打印crash日志,因为 error 必然触发close 所以只须要在 close 生命周期中进行 reconnect办法。
ws.on("close", function close() { console.log("ai connect close"); reconnect(); /// 每隔5s 重连 }); ws.on("error", function error(error) { console.log("ai connect error", error); errorLogger.error("ai connect error", error); //打印crash日志 ws.close() });
-
readyState=3 不会触发close的生命周期,所以须要对其独自解决,一旦检测到 其为3,则 terminate()该websocket.当然还有一种解决方案,因为在websocket中有心跳包的存在,详见How to detect and close broken connections?,能够在接管到来自其余socketServer的’pong’的信号,则写一个定时器,如果规定工夫内,没有收到来自下一个的心跳包则 terminate 该socket
if (message === 'pong') { clearTimeout(aliveInterval); aliveInterval = setTimeout(function () { wsObj.wsAI.terminate() }, 10000 + 1000) }
ws/websocket 官网Tip: Use
WebSocket#terminate()
, which immediately destroys the connection,
instead ofWebSocket#close()
, which waits for the close timer.
之我的了解: terminate() 可能立马 destory 连贯,如果是close()的话,意味着还须要期待 close 的工作工程化 Tips:
- 当咱们搭建 websocketServer的时候,经常会遇到socket.readyState =0 的状况, 会报Error: WebSocket is not open: readyState 0 (CONNECTING)这个谬误,所以在咱们和每个socket通信的时候,能够减少前提 ws.readyState===1 才进行ws.send(),否则socket中断,如何socket发送方没有做socket重连的话,会导致服务的解体。
- 咱们能够实时检测是否有 readyState ===2 或者 readyState ===3 的socket连贯,被动去执行ws.terminate(),因为在实战的过程中,发现某个socket状态继续为 2(即closing),而不是3(closed)
最初 放上两个websocket的nodejs的框架
1 https://socket.io/
- https://github.com/websockets/ws
发表回复