WebSocket相关调研 - noodles-v6/myfqa GitHub Wiki

实现比较

Comparison_of_WebSocket_implementations

如何保证连接是keepalive的

这里是来自w3的讨论

引用讨论

In case the network connection goes down (for example the ADSL dies), the WebSocket client could not realize of it until it attempts to send a new WS frame (it happens sometimes because there is not a TCP disconnection).

By sending periodical WS Ping frames from client to server, the client could realize of the network issue in a reasonable time.

As a suggestion, the WS API could include an interval for sending Ping frames to the server:

var myWebSocket = new WebSocket("ws://some-domain.com");
myWebSocket.set_monitor_interval(120);

Be careful with that. Imagine the WS client sends a WS Ping in the same moment the WS server is sending a very text frame to the client (let's say 10 MB). Due to the WS protocol design, the server cannot send a new frame (neither a Pong frame !!!) until the current frame is totally sent to the client.

So the client could receive the Pong frame long time after it sent the Ping frame. If it raises an onerror/onclose event, it would cause problems.

Take into account that current WS Ping/Pong is just valid as a keep-alive but not as a heart-beat mechanism (see comment above in which is explained that a WS Pong could be received much later due to an existing long WS message being already carried from).

So yes, making the browsers to send periodical WS Ping framse by default is useful IMHO. Maybe the interval could be configured (advanced configuration) within the browser configuration.

来自stackoverflow里的问答

摘要:

However, if you control both the client and server code, then you can easily add ping/pong support at a higher level.

Ping is meant to be sent only from server to client, and browser should answer as soon as possible with Pong OpCode, automatically. So you have not to worry about that on higher level.

这里需要重点了解下TCP相关知识点

为什么要了解TCP?因为WebSocket是基于tcp的,根据协议描述,除了handshake动作是走http的,连接建立后,所有行为都是基于tcp的。

好,下面是tcp的一些知识点。

  1. tcp有长短之分。注意,tcp只是提供了长短连接的功能,而如何保证连接是keepalive的,往往是应用层自己实现的,如http。