How to use ping / pong in Java Websocket

0

I searched for material on the Web but I still have not found how to implement ping / pong messages on the Server and Client, respectively.

I know how to send and receive, but I still do not understand the logic of it all. Can anyone help me with this?

    
asked by anonymous 19.08.2014 / 22:21

1 answer

1

If you plan to implement this at the application level, take a look at these Tyrus unit tests . The idea is very simple, create the logic of messages on the server side:

@ServerEndpoint(value = "/pingpong")
public static class PingPongEndpoint {

    private static final String PONG_RECEIVED = "PONG RECEIVED";

    @OnMessage
    public void onPong(PongMessage pongMessage, Session session) {
        try {
            session.getBasicRemote().sendText(PONG_RECEIVED);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnMessage
    public void onMessage(Session session, String message) throws IOException {
        session.getBasicRemote().sendPing(null));
    }
}

The client side sends pings (for example, from time to time):

session.getBasicRemote().sendPing(null);

And check if the server sent a pong:

session.addMessageHandler(new MessageHandler.Whole<PongMessage>() {
    @Override
    public void onMessage(PongMessage message) {
        System.out.println("### Client - received pong \"");
    }
});

If pong did not arrive after a while your connection was probably interrupted. It is recommended that you try to close it and reconnect.

You can also do the reverse, send server pings to the client and wait for pongs; if they do not arrive they can close the connection with the client. And of course the client can be in any other language.

You also do not need to be stuck with PongMessages and sendPing , you can create your own messages (with sendText , sendBinary , sendObject , etc).

If you'd like to do this purely at the Control Frames level and do not mind consuming APIs standard , take a look at TyrusWebSocket and methods onPing , onPong , sendPing and sendPong , however, do not expect all browsers to respond correctly to pings with pongs, let alone send pings on their own to keep the connection alive.

    
20.08.2014 / 04:41