I use Spring's WebSocketConnectionManager to work with WebSockets. Sometimes the connection closes and I have to reconnect. But I didn't find any proper solution to do that. Can I use WebSocketConnectionManager for restore (reconnect to) session? In the sources I see, that connection establishes by the following code:
@Override
protected void openConnection() {
if (logger.isInfoEnabled()) {
logger.info("Connecting to WebSocket at " + getUri());
}
ListenableFuture<WebSocketSession> future =
this.client.doHandshake(this.webSocketHandler, this.headers, getUri());
future.addCallback(new ListenableFutureCallback<WebSocketSession>() {
@Override
public void onSuccess(@Nullable WebSocketSession result) {
webSocketSession = result;
logger.info("Successfully connected");
}
@Override
public void onFailure(Throwable ex) {
logger.error("Failed to connect", ex);
}
});
}
And I'm using this Manager when my spring boot application start by:
WebSocketConnectionManager connectionManager = new WebSocketConnectionManager(
new StandardWebSocketClient(), webSocketHandler, "wss://localhost:8080/ws/");
connectionManager.start();
But what I have to do when connection closes? I tried to copy a piece of code from openConnection(), and use it for update the session directly in webSocketHandler, and it works. But it looks like dirty workaround.
Does anybody know how to do it correctly? Thank you.
In one of my projects, I came around similar situation. So, I resorted on using start() and stop() method with access to WebSocketManager as a bean in a connection manager class. I'd created a sample project for websocketserver and websocketclient sometime back. Just added reconnect feature to it.
Also, I was not reconnecting on every connection close. Only on close status 1006(Abnormal Closure), 1011(Internal Error) and 1012(Service Restart).
The project can be directly downloaded and run.