在我的应用程序中,我在标题中有一个“上次访问时间”字段,每 5 秒更新一次。我已将 header.jsp 包含在其他 jsps 中。[link1.jsp 和 link2.jsp.Refer 屏幕截图。] 现在,在加载时,我向服务器发出请求,请求被挂起。// 参考附加的 .js 文件和 .java 文件 它工作正常。我每 5 秒收到一次来自服务器的响应。现在,当我通过单击链接导航到其他 jsp 时,页面会重新加载,即 header.jsp 会重新加载。即使是现在,我也会收到来自服务器的响应,但不是每 5 秒一次,即使是在初始页面加载期间发起的请求,我也会收到响应。因此,尽管该字段每 2 秒更新一次,而不是 5 秒的实际间隔,但它似乎出现了。当我通过单击链接来回导航时,
有没有办法避免这种情况?
我打算在再次加载 header.jsp 时取消所有先前的请求。我尝试将 unsubscribe() 与长轮询结合使用。它没有用。
此外,我尝试根据此链接调用“/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);
}
大气资源.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";
}
}
截屏