Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does onFailure automatically close the WebSocket connection in OkHttp?

I'm using the OkHttp library for WebSocket connections in Java, and I'm wondering if the onFailure method included in the WebSocketListener class will close the WebSocket connection by default or if I need to manually close the connection myself.

Here's my implementation of the onFailure method:

    public void onFailure(@NonNull WebSocket webSocket, @NonNull Throwable t, @Nullable Response response) {
        super.onFailure(webSocket, t, response);
        if (!webSocket.close(1000, "Connection closed")) {
            webSocket.cancel();
            close();

        }
    }

As you can see, I'm manually calling the webSocket.close() method to close the WebSocket connection with a specified status code and reason. I've also included an if statement to check if the WebSocket connection is still open before closing it, and I'm calling the cancel() method to free up any resources held by the WebSocket connection if the close method returns false.

So, my question is: does the onFailure method automatically close the WebSocket connection in OkHttp, or do I need to manually close the connection myself as I've done in my implementation?

like image 338
David Feldman Avatar asked Mar 03 '26 17:03

David Feldman


1 Answers

The onFailure listener doesn't close the WebSocket. The onFailure listener tells you that the WebSocket has been closed due to an unexpected error.

According to the documentation on WebSocketListener.onFailure(),

Invoked when a web socket has been closed due to an error reading from or writing to the network. Both outgoing and incoming messages may have been lost. No further calls to this listener will be made.

Since the WebSocket is already closed, calling webSocket.close(1000, "Connection closed") inside the onClosed or onFailure will do nothing.

Also, according to the WebSocket.close() documentation, calling webSocket.cancel(); inside your onFailure listener also does nothing:

Immediately and violently release resources held by this web socket, discarding any enqueued messages. This does nothing if the web socket has already been closed or canceled.

like image 120
R_Shobu Avatar answered Mar 05 '26 05:03

R_Shobu