atmosphere icon indicating copy to clipboard operation
atmosphere copied to clipboard

[jQuery] streaming,network disconnected abruptly, disconnect not fired

Open PavelR577 opened this issue 14 years ago • 13 comments

I have a strange issue on my prod server.

  1. I open a streaming connection.
  2. after a random period of time (can happen after 30 seconds or after 5 minutes) the onDisconnect event is fired on the server.
  3. the connection stays open even after the resource is resumed (I can see this in firebug and even analyzing the firexfox connections using netPeeker).

this happens ONLY to the second subscriber and not to the first one (the one that created the channel) - not sure how it's related.

I can't reproduce it locally - I'm using the beta4 version - has anyone expereienced this issue? or maybe a related bug was closed since this version?

I'm using tomcat 7.0.29 on windows server 2008 x64.

update - forgot to add that the server is configured in NLB - I think the issue is at the network level.

any ideas?

PavelR577 avatar Sep 09 '12 15:09 PavelR577

ok it happens even if I pass the load balancer and go directly to specific node.

Is it possible that atmosphere sends wrong event? (calls the disconnect although the connection is still open)

I'll try to debug it with wireshark and see if the connection stays open on the server.

PavelR577 avatar Sep 10 '12 07:09 PavelR577

ok - found something interesting, if I unplug the network cable the disconnect event is not fired in the client side and the browser thinks the connection is active - is this normal? (If I disconnect the network adapter in windows then the disconnect event is fired normally)

PavelR577 avatar Sep 10 '12 09:09 PavelR577

looks like a bug in atmosphere - the client doesn't detect disconnection when the network disconnected abruptly (disconnect network cable for example)

going to write a fix and I'll post it here later.

PavelR577 avatar Sep 10 '12 10:09 PavelR577

Great (for the patch!!!). Will integrate and release it in 1.0.1

jfarcand avatar Sep 10 '12 12:09 jfarcand

when the network disconnects abruptly the browser still thinks the connection is active, so the only way (In my opinion) to know if the connection is alive or not it to actively monitor it on the client side.

the solution is simple, at certain periods I send some string from the server to the client (even if no one is broadcasting anything) and saving the last time we got the message, so as long as I'm getting messages from the server I assume the connection is ok, otherwise I close and restart it.

In my case, my message delimiter is @ so every 25 seconds I send this string (which is actually an empty message) to the client (if someone is broadcasting to the channel then no need to send this) which updates the lastPingTime.

Here is the code I've added (you'd probably have to rearrange it since it was written for my use case):

BroadcasterCacheBase.java (need to exclude the empty message from the cache)

public final synchronized void addToCache(
            final AtmosphereResource resource, final Object object) {
        logger.trace("Adding message for resource: {}, object: {}", resource, object);

        if (!object.toString().equalsIgnoreCase(DistributedBroadcaster.messageDelimiter)) { //dont cache the ping messages
            CachedMessage cm = new CachedMessage(object, System.currentTimeMillis(), null);
            CachedMessage prev = null;
            if (!queue.isEmpty()) {
                prev = queue.get(queue.size() - 1);
            }

            if (prev != null) {
                prev.next(cm);
            }

            // Some indexing issue if this return true
            if (!queue.contains(cm)) {
                queue.add(cm);
            }

            if (prev == null) {
                cm = new CachedMessage(true);
            }

            cache(resource, cm);
        }
    }

Broadcaster.java (my own broadcaster implementation)



private final Map<String, ClientPing> channelLastActivityMap = new HashMap<String, ClientPing>();
public static final String messageDelimiter = "<@>";

public Broadcaster(String id, AtmosphereConfig config) {
        super(id, config);

        if (id.startsWith("user_")) // only for the main channel (we assume it's esablished first on every page)
            channelLastActivityMap.put(id, new ClientPing());

    }
  @Override
    public <T> Future<T> broadcast(T msg) {
        pingClient();
        return super.broadcast(msg);
    }

private void pingClient() {
        ClientPing alive = channelLastActivityMap.get(getID());
        if (alive != null)
            alive.ping();
    }

    class ClientPing {
        private long lastBroadcast;

        ClientPing() {
            this.lastBroadcast = System.currentTimeMillis();

            new Thread(new Runnable() {
                public void run() {
                    //if message not broadcaster during X seconds then send char to the client
                    while (true) {
                        try {
                            System.out.println("channel" + getID() + " diff:" + (double) ((System.currentTimeMillis() - getLastBroadcast()) / 1000));
                            if ((System.currentTimeMillis() - getLastBroadcast()) / 1000 > PING_TIMEOUT_SEC && getAtmosphereResources().size() != 0) {
                                broadcast(messageDelimiter);
                            }
                            Thread.sleep(1000);
                        } catch (Exception e) {
                            logger.error("ClientPing", "error pinging client", e);
                        }
                    }
                }
            }).start();

        }

        public long getLastBroadcast() {
            return lastBroadcast;
        }

        public void ping() {
            this.lastBroadcast = System.currentTimeMillis();
        }
    }


jquery.atmosphere.js:

//I've added these to the _request object:
                pingTimeout : 35, //in seconds
                lastPingTime:0,

in trackMessageSize func need to update the last ping time:

//any message from the server will reset the last ping time
request.lastPingTime = (new Date()).getTime();

after the request is suspended need to monitor the connection:

 if (rq.suspend) {
                        rq.id = setTimeout(function() {
                            if (_subscribed) {
                                ajaxRequest.abort();
                                _subscribe(rq);
                                _execute();
                            }
                        }, rq.timeout);

                        //todo: fix for closing connection when network goes down abruptly
                        rq.lastPingTime = (new Date()).getTime();
                        rq.ping = setTimeout(function() {
                            detectDeadConnection(ajaxRequest, rq);
                        }, rq.pingTimeout * 1000);
                    }

and finally the monitor function:

/**
             * keep track of last message that we got from the server, if reached pingTimeout - restart!
             * @param ajaxRequest Ajax request.
             * @param request Request parameters.
             * @param create If ajax request has to be open.
             */
            function detectDeadConnection(ajaxRequest, rq) {
                var pingPassed = (new Date().getTime() - rq.lastPingTime) / 1000;
                if (jQuery.atmosphere.connected && pingPassed > rq.pingTimeout) {//if connected and no ping we'll assume connection was stopped abruptly and reset it manually
                    ajaxRequest.abort();
                    _subscribe(rq);
                    _execute();
                }
                clearTimeout(rq.ping);
                rq.ping = setTimeout(function() {
                    detectDeadConnection(ajaxRequest, rq);
                }, (rq.pingTimeout - pingPassed) * 1000); //take into account the time passed from the last ping
            }

PavelR577 avatar Sep 10 '12 15:09 PavelR577

OK, I like your approach. Can you do pull request? I will create a new Broadcaster than extend the DefaultBroadcaster and add the functionality you are looking for (being able to enable the


        if (id.startsWith("user_")) // only for the main channel (we assume it's esablished first on every page)
            channelLastActivityMap.put(id, new ClientPing());

I know you are working on a fork, but if I can release 1.0.1 will all your patches/fixes that way you won't have to support your code locally.

jfarcand avatar Sep 10 '12 17:09 jfarcand

How do I do a pull request? this is my first time :)

By the way, this solution can also be used to solve the issue of IE not knowing when the server was turned off (I did a fix for it also - I'll post it when I'll finish testing :) )

PavelR577 avatar Sep 10 '12 20:09 PavelR577

See this. Mainly you fork, apply your change and click the button. Thanks!

jfarcand avatar Sep 10 '12 20:09 jfarcand

having issues with the pull... I'll try later on this week (hopefully I'll have time).

In the mean time I can just post the fixes here or send you the whole project.

PavelR577 avatar Sep 11 '12 14:09 PavelR577

Send me the changes you did as a .zip to [email protected]. Thanks!

jfarcand avatar Sep 11 '12 15:09 jfarcand

I don't think that its a good idea to ping the client from the server. Client should ping the server and server must close the connection when the client doesn't ping after some timeout.

hapali avatar Dec 13 '12 22:12 hapali

@hapali So far this hasn't been integrated. I favorite the heatbeat interceptor instead.

jfarcand avatar Dec 13 '12 23:12 jfarcand

Fixed in 1.0.10.

jfarcand avatar Feb 12 '13 14:02 jfarcand