2016-05-23 110 views
0

我使用spring websocket stomp客戶端。下面是一個代碼片段:春季websocket stomp客戶端如何捕獲連接丟失?

List<Transport> transports = new ArrayList<Transport>(2); 
transports.add(new WebSocketTransport(new StandardWebSocketClient())); 
transports.add(new RestTemplateXhrTransport()); 

WebSocketHttpHeaders headers = new WebSocketHttpHeaders(); 
headers.add("Cookie", client.getCookieString()); 

SockJsClient sockJsClient = new SockJsClient(transports); 

WebSocketStompClient stompClient = new WebSocketStompClient(sockJsClient); 
stompClient.setMessageConverter(new StringMessageConverter()); 
ListenableFuture<StompSession> future = 
    stompClient.connect(configuration.getApp().getWebsocketServerBase() + "/websocket/sa", headers, new MyWebSocketHandler()); 

future.addCallback(new SuccessCallback<StompSession>() { 
    public void onSuccess(StompSession stompSession) { 
     System.out.println("on Success!"); 
    } 
}, new FailureCallback() { 
    public void onFailure(Throwable throwable) { 
     System.out.println("on Failure!"); 
    } 
}); 

它的工作原理,但是當WebSocket的服務器關閉時,客戶端沒有收到該消息。

如何監聽服務器關閉事件?

回答

2

我找到了解決方案。

MyWebSocketHandler實現StompSessionHandler這樣的:

private class MyWebSocketHandler implements StompSessionHandler { 
    @Override 
    public void afterConnected(StompSession stompSession, StompHeaders stompHeaders) { 

    } 

    @Override 
    public void handleException(StompSession stompSession, StompCommand stompCommand, StompHeaders stompHeaders, byte[] bytes, Throwable throwable) { 
    } 

    @Override 
    public void handleTransportError(StompSession stompSession, Throwable throwable) { 
     if (throwable instanceof ConnectionLostException) { 
      // if connection lost, call this 
     } 
    } 

    @Override 
    public Type getPayloadType(StompHeaders stompHeaders) { 
     return null; 
    } 

    @Override 
    public void handleFrame(StompHeaders stompHeaders, Object o) { 
    } 
} 

你可以看到方法handleTransportError。謝謝。

參考Spring WebSocket Document 25.4.13 STOMP客戶端。

+0

ConnectionLostException:當STOMP會話的連接丟失而不是關閉時引發。 我使用它。 參考: http://docs.spring.io/autorepo/docs/spring/4.3.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/messaging/simp/stomp/package-summary.html – Sergio

0

我想你也能趕上SessionDisconnectEvent

SessionDisconnectEvent - 出版時STOMP會話結束。 DISCONNECT可能已從客戶端發送,或者也可能在WebSocket會話關閉時自動生成。在某些情況下,此事件可能會在每個會話中多次發佈。對於多個斷開連接事件,組件應該是冪等的。

+0

I會嘗試一下,謝謝你的回答。 –