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.