Websocket connection closed automatically – keepalive Ping example

Websocket connection closed automatically – keepalive Ping example

This tutorial guides you on how to handle Websocket connection closed automatically when there is not data transfer from the client to the server. Let’s learn how to implement keepalive with example. Therefore the Websocket connection will not get closed even when there is no data transfer between client and server after the connection is established.

Websocket connection closed automatically – keepalive Ping example

In the following example without keepalive implementation the Websocket connection was getting closed or disconnected by server after some time.

// This method return a new websocket tunnel which uses connected socket
MyWebSocketTunnel tunnel = new MyWebSocketTunnel(socket);

//Read access
MyWebSocketReader reader = tunnel.getSocketReader();
try{
  char[] message;
  do {

    message = reader.read();
    System.out.println(message);
    
    if(tunnel.hadReaderThreads())
      break;
  } while (tunnel.isOpen() && (message = reader.read()) != null);

}catch(exception e){
  e.printStackTrace();
}

For instance, since there is no keepalive implementation in the above example the connection will get timed out after 15 seconds and websocket connection will get closed automatically. As you can see that disconnect instruction has been received by the client and connection is closed.

4.size,1.0,4.2560,4.1024;
3.img,1.1,2.12,2.-1,9.image/png,1.0,1.0;
3.end,1.1;
----
----
4.sync,9.641163649
4.sync,9.641165652
10.disconnect

Therefore, we need to implement keepalive. This logic keep sending ping messages from the client to the server to make the connection keepalive.

TCP/ Websocket Keepalive PING Example

Now the modified example with keepalive implementation will look like below.

// This method return a new websocket tunnel which uses connected socket
MyWebSocketTunnel tunnel = new MyWebSocketTunnel(socket);

//call keepalive method
startTCPKeepAlive(socket, tunnel);

//Read access
MyWebSocketReader reader = tunnel.getSocketReader();
try{
  char[] message;
  do {

    message = reader.read();
    System.out.println(message);
    
    if(tunnel.hadReaderThreads())
      break;
  } while (tunnel.isOpen() && (message = reader.read()) != null);

}catch(exception e){
  e.printStackTrace();
}

The startTCPKeepAlive() method uses java.util.Timer.

privtae static void startTCPKeepAlive(MySocket socket, MyWebSocketTunnel tunnel) {
  Timer keepAliveTimer = new Timer ("PING TIMER");
  MuWebSocketWriter writer = tunnel.getSockerWriter();
  keepAliveTimer.scheduleAtFixedRate(new TimerTask(){
    @Override
    public void run() {
      if(socket.isOpen() == false){
        keepAliveTimer.cancel();
        keepAliveTimer = null;
        return;
      }

      System.out.println("Send keep alive ping");
      Date date = new Date();
      long timeMilli = date.getTime();
      String pingMesage = "0.,4.ping,13."+timeMilli+";";
    
      try{
         writer.write(pingMessage.toCharArray(), 0, pingMessage.length());
      } catch(Exception e){
         e.printStackTrace();
      }
    }
  },5000, 5000}
  
}

The above method will start a timer task to send ping message for every 5 seconds to the server to keep the websocket connection keepalive. Therefore, the websocket connection will not get closed even after 15 seconds timeout period.

This is how I handled Websocket connection getting closed automatically.

Hope it helped 🙂

You’ll also like:

References:

guest
0 Comments
Inline Feedbacks
View all comments