我使用spring 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服务器关闭时,客户端不会收到消息。
如何监听服务器关闭事件?
答案 0 :(得分:3)
我找到了解决方案。
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。谢谢。
参考https://github.com/d3/d3/wiki/Histogram-Layout 25.4.13 STOMP客户端。
答案 1 :(得分:0)
我认为你也可以抓住SessionDisconnectEvent:
SessionDisconnectEvent
- 在STOMP会话结束时发布。 DISCONNECT可能已从客户端发送,也可能在WebSocket会话关闭时自动生成。在某些情况下,每个会话可能会多次发布此事件。对于多个断开连接事件,组件应该是幂等的。