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:
- Java 8 : Find union and intersection of two Lists (ArrayLists)
- How to manipulate Java 8 Stream data sources or objects?
- Add or install local jar files to the Maven Project ?
- Replace element in ArrayList at specific index
- Convert Integer List to int array
- ArrayList removeAll() method not removing elements
- Convert floating point number to fixed point in Python
- What is %matplotlib inline and how to use ?
- Java String substring() example program
- Add python3 kernel to jupyter IPython notebook ?
- Reset jupyter notebook theme to default theme
- How to change the default theme in Jupyter Notebook ?
- To run Jupyter Notebook on Windows from command line
- Run a Jupyter Notebook .ipynb file from terminal or cmd prompt
- Amazon Linux AMI : apt-get command not found
- Check if a file or folder exists without getting exceptions ?
- Python program to find the greatest of three numbers
- Putty Fatal Error No supported authentication methods available
- Find which users belongs to a specific group in linux
- Check if Python Object is a Number ?
- Remove non-numeric characters from string in Python
- Convert negative to positive number in Python
- Extract numbers from a string in python
- Program to Check Given Number is Odd or Even