Search code examples
jquerywebsocketcometd

Reduce time to check jquery cometd meta connect?


How can we reduce the time to fire meta/connect listeners in jquery cometd? I have a scenario when the signal strength is low, I want to display a message. But in cometd the connection is hanged before going to disconnect state. I referred the documentation but couldn't find a good solution.


Solution

  • A CometD client application can detect if the connectivity with the server is broken by registering a listener on the /meta/connect channel:

    cometd.addListener('/meta/connect', function(m) {
        connectionBroken = !m.successful;
    });
    

    CometD works in a way that a /meta/connect message is sent with a period determined by the server timeout configuration parameter, by default 30 seconds. The server "holds" the reply, and only replies to this message as soon as it has a broadcast message to deliver back to the client, or after the timeout elapsed.

    What described above is the "heart-beat" mechanism implemented by CometD, and there is no need for applications to re-implement another heart-beat mechanism - it will not be any more efficient than CometD's.

    If the TCP connection is closed (by the client, by the server, or by an intermediary) while the reply is being "held" by the server, the client should immediately detect it (this depends on the client implementation - browsers may delay this notification), and CometD will notify the listener above.

    If the TCP connection is zombie, that is packets are dropped, there is no TCP notification that the connection has been closed, etc. then CometD waits at most timeout + maxNetworkDelay (see https://docs.cometd.org/current/reference/#_javascript_configure), then CometD will notify the listener above.

    If your application publishes messages while the connection is zombie, CometD waits at most maxNetworkDelay, then fails the message callback (see https://docs.cometd.org/current/reference/#_javascript_publish).

    Unfortunately, zombie connections are a real pain to detect; with some careful coding, however, CometD allows you to detect them within maxNetworkDelay, more or less, with a mixed usage of a /meta/connect listener and message callbacks.

    Be careful that a too small maxNetworkDelay can cause a lot of false detections for broken connections.

    To sum up, precise coding using a /meta/connect listener and message callbacks, paired with tuning of maxNetworkDelay should give applications the ability to detect connectivity problems as fast as possible without (too many) false reports.