Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reconnect websocket in java?

Tags:

java

websocket

I have a simple WebSocket client in java. Sometimes the connection to WebSocket server may be lost. How to auto-reconnect if the connection is lost?

import javax.websocket.*;
import java.net.URI;

@ClientEndpoint
public class WebsocketClientEndpoint {

Session userSession = null;

public WebsocketClientEndpoint(URI endpointURI) {
    try {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        container.connectToServer(this, endpointURI);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

@OnOpen
public void onOpen(Session userSession) {
    System.out.println("Opening websocket");
    this.userSession = userSession;
}

@OnClose
public void onClose(Session userSession, CloseReason reason) {
    System.out.println("Closing websocket");
    this.userSession = null;
}

@OnMessage
public void onMessage(String message) {
    System.out.println("Received message: "+ message);
}

public void sendMessage(String message) {
    this.userSession.getAsyncRemote().sendText(message);
}
}

Test app

import java.net.URI;
import java.net.URISyntaxException;
public class TestApp {

public static void main(String[] args) {
    try {
        final WebsocketClientEndpoint clientEndPoint = new WebsocketClientEndpoint(new URI("ws://localhost:8080/websocket/api"));

        while (true) {
            Thread.sleep(30000);
        }

    } catch (Exception ex) {
        System.err.println("Exception: " + ex.getMessage());
    }
}
}

There are simple WebSocket client and test class in java. Sometimes the connection to WebSocket server may be lost. How to auto-reconnect if the connection is lost?

like image 931
DavidJoker Avatar asked Aug 10 '26 19:08

DavidJoker


2 Answers

Reconnect is not part WebSocket JSR 356 Specs and has to be implemented by writing specific logic.

However, you can use client libraries like 'Tyrus' which have a ReconnectHandler. Basically, this has APIS to capture events like onDisconnect , onConnectFailure which could be used to reconnect.

See this link on how to use it : Tyrus Reconnect Handler

API Doc Here

like image 179
TechFree Avatar answered Aug 12 '26 12:08

TechFree


As pointed out by TechFree reconnecting is not part of JSR 356 Specs. Actually, This implementation was done on purpose. The reason being a socket connection is written in a way it can survive an atomic bomb's destruction.

As described connection to the server can be lost due to a plethora of reasons mainly due to Network, server-side issues, Protocol violations, or Security issues.

So the only option we are left with is to create a new connection to the server and use that for communication. Now assuming there can be a situation where a connection cannot be established due to server-side or network issues then we will need a max retry kind of logic that limits the connection creation before giving up.

Now assuming at some time suppose T, your server is able to establish a connection (post recovery) then it needs to notify the client regarding the same. (Or writing some client-side logic which tries to attempt to connect after some interval)

To sum up there are no shortcuts to writing an ample amount of code that takes care of reconnection and retry logic when it comes to Websockets. Hope this helps.

like image 27
Suchandra T Avatar answered Aug 12 '26 12:08

Suchandra T