I'm not sure if you have solved this issue but I managed to come up with a solution to reconnect a WebSocket connection.
For my scenario, I would like to reconnect my WebSocket connection if @OnWebSocketError method is triggered. Initially I implemented it like this
Implementation A:
@OnWebSocketError
public void onError(Throwable e) {
someMethodToReconnect();
}
and inside someMethodToReconnect
if (client == null) {
client = new WebSocketClient(sslContextFactory);
client.setMaxIdleTimeout(0);
}
if (socket == null) {
socket = new ReaderSocket(); // ReaderSocket is the name of my @WebSocket class
}
try {
client.start();
client.connect(socket, new URI(socketUrl), request);
} catch (Exception e) {
LOGGER.error("Unable to connect to WebSocket: ", e);
}
However, this led to another issue. There are 2 types of error thrown back to me if the server is not up. The exceptions are java.net.ConnectException and org.eclipse.jetty.websocket.api.UpgradeException.
The flow would be:
- Initial request to WebSocket server (server is not up)
java.net.ConnectException thrown
org.eclipse.jetty.websocket.api.UpgradeException thrown
And in Implementation A, someMethodToReconnect would be called twice.
This led to Implementation B
@OnWebSocketError
public void onError(Throwable e) {
if (e instanceof ConnectException) {
// Attempt to reconnect
someMethodToReconnect();
} else {
// Ignore upgrade exception
}
}
So far Implementation B works fine, however I'm trying to find out if there's any other exceptions that would be thrown.