在订阅之前取消订阅之前的请求

时间:2013-07-17 12:50:17

标签: java websocket atmosphere

在我的应用程序中,标题中有一个字段“上次访问时间”,每5秒更新一次。我已将header.jsp包含在其他jsps中。 [link1.jsp和link2.jsp.Refer截图。] 现在,在加载时,我向服务器发出请求,请求被暂停。 //引用附加的.js文件和.java文件 它工作正常。我每5秒钟从服务器得到一个响应。 现在,当我通过单击链接导航到其他jsps时,页面将被重新加载,即header.jsp被重新加载。即使是现在,我从服务器得到响应,但不是每5秒, 即使对于在初始页面加载期间启动的请求,我也会得到响应。因此,尽管该字段每2秒更新一次而不是实际的5秒间隔,但仍会出现。 当我通过点击链接来回来回导航时,时钟会不断变化,有些请求会在不同的时间间隔内被触发。

有没有办法避免这种情况?

我打算在再次加载header.jsp时取消之前的所有请求。我尝试将unsubscribe()与长轮询结合使用。它不起作用。

此外,我尝试按照此link调用“/ stop”url并在其回调中考虑触发请求,以便每次都可以重新启动请求。即使这样也行不通。调用“/ stop”会阻止请求被触发。从未调用过回调。

我不确定我在这里遗失了什么。

请帮帮我。

感谢。

js代码

$("document").ready(function(){
fireRequest();
});
function fireRequest()
{
var socket = $.atmosphere;
var subSocket;
var websocketUrl = "atmos/time";
var request = { 
        url: websocketUrl,
        contentType : "application/json",
        logLevel : 'debug',
        dataType: 'json',
        shared:true,
        transport : 'websocket' ,
        trackMessageLength : true,
        enableProtocol : true,
        reconnectInterval : 0,
        maxReconnectOnClose : 3,
        dropAtmosphereHeaders : false,
        timeout : 10 * 60 * 1000,
        fallbackTransport: 'long-polling',
        connectTimeout: -1
    };
    request.onMessage = function (response) {
    try {
        var data = response.responseBody;
        $("#time").text(data);
    }
    catch(e)
    {
        console.log(e);
    }

};
request.onOpen = function(response) {
    console.log('onOpen '+ response);           
};
request.onReconnect = function (request, response) {
    console.log('onReconnect ' + request);
    console.log('onReconnect ' +  response);
};
request.onClose = function(response) {
    if (response.state == "unsubscribe") {
       alert('window switch');
    }
    console.log('onClose ' + response);
},

request.onError = function(response) {
    console.log('onError ' + response);
};
subSocket = socket.subscribe(request);
}

AtmosphereResource.java

@Path("/{tagid}")
@Produces("text/html;charset=ISO-8859-1")
@Singleton
public class AtmosResource {

private static final Logger logger = LoggerFactory.getLogger(AtmosResource.class);
private final AsyncHttpClient asyncClient = new AsyncHttpClient();
private final ConcurrentHashMap<String, Future<?>> futures = new ConcurrentHashMap<String, Future<?>>();
private final CountDownLatch suspendLatch = new CountDownLatch(1);
private int count = 1;

@GET
public SuspendResponse<String> search(final @PathParam("tagid") Broadcaster feed,
                                      final @PathParam("tagid") String tagid, final @Context AtmosphereResource resource) {

    if (feed.getAtmosphereResources().size() == 0) {
        final Future<?> future = feed.scheduleFixedBroadcast(new Callable<String>() {
            public String call() throws Exception {
                suspendLatch.await();
                asyncClient.prepareGet("http://localhost:7070/sample/rest/currentTime").execute(
                        new AsyncCompletionHandler<Object>() {

                            @Override
                            public Object onCompleted(Response response) throws Exception {
                                String s = response.getResponseBody();
                                if (response.getStatusCode() != 200) {
                                    feed.resumeAll();
                                    feed.destroy();
                                    return null;
                                }
                                feed.broadcast(s).get();
                                System.out.println("Current Count::: " + count);
                                count ++;
                                System.out.println("data:: " + new Date().toString());
                                return null;
                            }
                        });
                return null;
            }
        }, 5, TimeUnit.SECONDS);
        futures.put(tagid, future);
    }
    return new SuspendResponse.SuspendResponseBuilder<String>().broadcaster(feed).outputComments(true)
            .addListener(new EventsLogger() {
                @Override
                public void onSuspend(
                        final AtmosphereResourceEvent event) {
                    super.onSuspend(event);
                    feed.addAtmosphereResource(resource);
                    suspendLatch.countDown();
                }
                // overriding this method to check when the user 
                //switches tabs/closes browser.
                //ref: https://github.com/Atmosphere/atmosphere/wiki/Detecting-Browser-close%27s-situation-when-using-long-polling
                @Override
                public void onDisconnect(final AtmosphereResourceEvent event) 
                {
                    String transport = event.getResource().getRequest().getHeader(HeaderConfig.X_ATMOSPHERE_TRANSPORT);
                    if (transport != null && transport.equalsIgnoreCase(HeaderConfig.DISCONNECT)) {
                         System.out.println("DISCONNECT");
                    } else {
                         System.out.println("Long-Polling Connection resumed."); 
                    }
                }
            }).build();
}

@GET
@Path("stop")
public String stopSearch(final @PathParam("tagid") Broadcaster feed,
                         final @PathParam("tagid") String tagid) {
    feed.resumeAll();
    if (futures.get(tagid) != null) {
        futures.get(tagid).cancel(true);
    }
    logger.info("Stopping real time update for {}", tagid);
    return "DONE";
}
}

截屏

enter image description here

1 个答案:

答案 0 :(得分:0)

我通过重写AtmosphereResourceEventListener的onDisconnect方法并将其附加到Suspended Response来实现它。

@Override
                public void onDisconnect(final AtmosphereResourceEvent event) 
                {
                    if (event.isCancelled() || event.isClosedByClient()) {
                        feed.resumeAll();
                        if (futures.get(tagid) != null) {
                            futures.get(tagid).cancel(true);
                        }
                    } 
                }

由于