hooks zhang hooks zhang - 6 months ago 364
Java Question

Spring websocket stomp client how to capture the connection is lost?

I use spring websocket stomp client. Below is a code fragment:

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


It works, but when websocket server is closed, the client doesn't receive the message.

How to listener server close event?

Answer

I have found the solution.

MyWebSocketHandler implements StompSessionHandler like this:

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

You can see method handleTransportError. Thank you.

Reference Spring WebSocket Document 25.4.13 STOMP Client.