How to reconnect websocket in java?

Viewed 4110

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?

1 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

Related