0

I have a simple websocket endpoint, using the javax.websocket library, but the method intercepting with the OnClose annotation is never called even though OnOpen and OnMessage are called. I've tried subclassing ServerEndpoint as well without any luck.

This is my code

@ServerEndpoint("/websocket/cont")
public class ContinousWebsocketExample {
    private static final Logger LOGGER = LoggerFactory.getLogger(ContinousWebsocketExample.class);

    private int counter = 0;
    @OnOpen
    public void onOpen(Session client, EndpointConfig config) {
        LOGGER.debug("---------------------------Opening websocket connection-----------------------------------");
        while (true) {
            client.getAsyncRemote().sendText("Counter is: " + counter);
            counter ++;
            LOGGER.debug(String.valueOf(client.isOpen()));
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @OnClose
    public void onClose(Session client, CloseReason reason) {
        LOGGER.debug("---------------------------Closing websocket connection-----------------------------------");
    }
}

And the relevant Javascript:

var socket = new WebSocket('ws://localhost:8080/examples/websocket/cont') socket.close();

The program keeps on printing the counter even after the frontend closed the socket. However, client.isOpen() returns false after the frontend has closed the connection.

Jesper
  • 472
  • 1
  • 4
  • 14
  • 1
    what happens if you do not have a never ending loop in `onOpen` – Scary Wombat Jun 26 '18 at 08:39
  • Yep, that was the issue. Nice catch! – Jesper Jun 26 '18 at 08:45
  • @ScaryWombat Do you know of any way to force close a websocket when it is doing work, except for having the interruption as a message? Because I'm assuming this same behavior will happen when the websocket server is doing some actual useful work as well. – Jesper Jun 26 '18 at 08:59

0 Answers0