0
I searched for material on the Web but I haven’t found how to implement ping/pong messages on the Server and Client respectively.
I know how to send and receive, but I still don’t understand the logic of it all. Can someone help me with that?
0
I searched for material on the Web but I haven’t found how to implement ping/pong messages on the Server and Client respectively.
I know how to send and receive, but I still don’t understand the logic of it all. Can someone help me with that?
1
If you are thinking of implementing this at the application level, take a look at these Unit tests of Tyrus. The idea is quite simple, create the server-side message logic:
@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));
}
}
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 has not arrived after a while your connection has probably been interrupted. It is recommended to try to close it and reconnect.
You can also do the reverse, send server pings to the client and wait for Pongs; if they don’t arrive you can close the connection with the client. And of course the customer can be in any other language.
You also don’t need to get stuck to PongMessages
and sendPing
, can create your own messages (with sendText
, sendBinary
, sendObject
, etc.).
If you would like to do this purely at the level of Control Frames and does not care about consuming API standard, take a look at the class Tyruswebsocket and in the methods onPing
, onPong
, sendPing
and sendPong
, however, don’t expect all browsers to respond correctly to pings with Pongs, let alone send pings on their own to keep the connection alive.
Browser other questions tagged java-ee websocket
You are not signed in. Login or sign up in order to post.
So to check the inactivity of the "I should implement" connection with ping/pong? For example, checking the ping response time (pong) to remove or not from the list of active connections.
– Luídne
Luídne, to be exact. Control Frames with opscode should already do this automatically for you, but, as I said, this is not very reliable (most browsers do not send the pings automatically, etc).
– Anthony Accioly