1
votes

According to this post [When does OnWebSocketClose fire in Jetty 9, OnClose fire for me correctly. but i can not reconnect, because I have not correct situation. (websocett is closed and I can not send any message)

where and when I can reconnect in websocket problem (close by network problem or timeout or kickout by sever after n seconds without handshaking)

1

1 Answers

2
votes

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:

  1. Initial request to WebSocket server (server is not up)
  2. java.net.ConnectException thrown
  3. 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.