oikonomiyaki
oikonomiyaki

Reputation: 7951

Stopping a WebSocket from sending data

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?

Upvotes: 0

Views: 594

Answers (1)

Joakim Erdfelt
Joakim Erdfelt

Reputation: 49452

Your code never lets the main Parse / Event Handling thread process anything else.

You never return from onConnect, which is mandatory.

Spin off a new thread to send those messages. That will allow the subsequent incoming frames from the remote to be processed by the implementation.

The session will become invalid when the close is detected. Either from a valid close handshake, or from an abnormal close, or from a harsh close.

You can also use while(session.isOpen()) { } as an added guard, but keep in mind that it ALSO requires the ability to process more incoming frames.

Upvotes: 1

Related Questions