2013-07-17 55 views
0

在我的應用程序中,我在頭部有一個字段「上次訪問時間」,每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"; 
} 
} 

截屏

enter image description here

回答

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); 
         } 
        } 
       } 

感謝