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.