I am using Jetty's WebSocket API to stream data to a client. Once the client connects to the server, the server will send json data periodically to the client.
@WebSocket
public class WSHandler {
// send data every 10 seconds
public static final long PERIOD = 10000L;
@OnWebSocketClose
public void onClose(int statusCode, String reason) {
}
@OnWebSocketError
public void onError(Throwable t) {
}
@OnWebSocketConnect
public void onConnect(Session session) {
System.out.println("Connect: " + session.getRemoteAddress().getAddress());
try {
while(...) {
session.getRemote().sendString(json);
Thread.sleep(PERIOD);
}
} catch (IOException | InterruptedException e ) {
e.printStackTrace();
}
}
@OnWebSocketMessage
public void onMessage(String message) {
}
}
What I want to do is once the client decides to terminate the connection, the server would stop sending the json data (it does stop, but it looks like not gracefully, throwing EOFException, IOException or broken pipe or something on the server side).
I already did try using a global boolean variable that turns false
in onClose
and placing that on while
loop, but that does not seem to work.
What should I put on onConnect
method's while loop to terminate the sending of data without throwing Exceptions?