在我的应用程序中,我在头部有一个字段“上次访问时间”,每5秒更新一次。我在其他jsps中包含了header.jsp。 [link1.jsp和link2.jsp.Refer截图。] 现在,在载入时,我向服务器发出一个请求,请求被暂停。 //引用附件.js文件和.java文件 它工作正常。我每5秒钟收到服务器的响应。 现在,当我通过单击链接导航到其他jsps时,页面被重新加载,即,header.jsp被重新加载。即使是现在,我也会收到服务器的回应,但不是每隔5秒钟,即使是在初始页面加载期间启动的请求,我也会收到回复。因此,虽然该字段每2秒更新一次,而不是实际的5秒间隔。 当我通过点击链接来回浏览时,时钟会不断点击,有不同的时间间隔发出请求。在订阅之前取消订阅之前的请求
有没有办法避免这种情况?
我打算取消所有先前的请求,当我再次加载header.jsp。我试图结合长轮询来取消订阅()。它没有工作。
此外,我试着调用“/ stop”url作为此link而且它的回调思路是关于发起请求,以便我可以每次重新启动请求。即使这样也行不通。调用“/ 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";
}
}
截屏