Search code examples
javawebsocketjava-ee-7

Websocket ClientEnpoint disconnect


I am using Wildfly 8.1 and I implemented a Websocket Server endpoint which works very well.

I can push and receive data without a problem. (Javascript clients)

Now I also need a client in java to connect to another system.

My Client looks like this:

@ClientEndpoint
public class WebsocketClient {
    public WebsocketClient() {
    }

    @OnOpen
    public void onOpen(Session session) {
        try {
            System.out.println("Sending test message to endpoint: " + new Date());
            session.getBasicRemote().sendText(name);
        } catch (IOException ex) {
            log.error(ex.getMessage(), ex);
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("Received: " + message);
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        log.info("Disconnected: " + closeReason));
    }

}

try {
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    String url = "ws://localhost:8080/test/wss/websocket_socket";
    container.connectToServer(BlockchainWebsocketClient.class, URI.create(url));
} catch (DeploymentException | IOException e) {
    e.printStackTrace();
}

The connect works, but I wonder how do I disconnect? The WebSocketContainer has no methods for that. How can I control the connect/disconnect/reconnect?

best regards, m


Solution

  • container.connectToServer(...)
    

    returns javax.websocket.Session instance, you can use it for calling session.close() if you want - that should disconnect current client session from server endpoint.

    Reconnect is not part of JSR 356 - Java API for WebSocket, so you must implement it by yourself or you some proprietary feature (Tyrus - other JSR 356 implementation - has something called "ReconnectHandler", WildFly might have something as well).