I've a Socket Program which acts as client. When it initializes connection, Server Sends data periodically and my program acknowledges back.
I've written my program in such a way, when there is an interruption in connection between Client-Server with Socket/network dis-connectivity, Client receives an event in the form of exception and I handle it and used recursions there to keep on looking for the connection to re-establish.
I've tested this with Hercules as a Server.
But when I actually deployed the application, After some certain time I see my program is no longer receiving the data though it is running. And server say Client has not initialized the connection.
So here what I presume is happening is the connection is Idle for long time, Client socket gets disconnected but event not received. Could this happen?
If so, How to handle this? I'm attaching the following example client socket program.
public void connect(String ipAddress, int portNo, int updateValue) {
Socket socket = null;
try {
System.out.println("Connecting ...");
//socket = new Socket("192.168.3.39",3000);
socket = new Socket(ipAddress,portNo);
System.out.println("Timeout: "+socket.getSoTimeout());
InputStream is = socket.getInputStream();
byte[] buffer = new byte[512];
try {
int read;
while((read = is.read(buffer)) != -1) {
System.err.println("The Lengh of the buffer is: "+buffer.length);
ByteArrayOutputStream outputBuffer = new ByteArrayOutputStream();
String output = new String(buffer, 0, read);
System.out.println(output);
outputBuffer.write(buffer, 0, read);
//Code snippet to write an integer into PLC
BufferedOutputStream bw = null;
try {
bw = new BufferedOutputStream(socket.getOutputStream());
bw.write(Convert.IntToByteArr(updateValue)); //Here I want to write only integers as bytes.
bw.flush(); //Flushing the data
System.out.println("Data Flushed");
} catch (Exception e) {
System.err.println("Exception: "+e.getMessage());
}
};
connect(ipAddress, portNo, updateValue);
} catch(SocketException e) {
System.err.println("SocketException: "+e.getMessage());
connect(ipAddress, portNo, updateValue);
}
System.out.println("******END*****");//This code will never be executed
} catch (ConnectException e) {
System.err.println("Connection Exception: "+e.getMessage());
connect(ipAddress, portNo, updateValue);
} catch (Exception e) {
System.err.println("Generic Exception: "+e.getMessage());
e.printStackTrace();
connect(ipAddress, portNo, updateValue);
}
}