There are some issues to check disconnection between server and client sockets in the programming area. Inspite of connection closed in real, read method does not give an error to BufferedReader() method like below;
if (bufferedReader.read()==-1 )
{
logger.info("CONNECTION TERMINATED!");
clientSocket.close();
setUpSocket(); //sets up the server to reconnect to the client
}else{
sendHeartBeat(); //Send a heartbeat to the client
}
Many programmer faced with that problem, so many other solutions come on board.. Set timeout, checking socket is available and anothers..
Here is my solution that checks manually: after sending a data to server then check connection still available. Here is the code:
try { DataOutputStream dos = new DataOutputStream(rc_sock.getOutputStream()); dos.write(data); // data was set before dos.flush(); return checkDisconnection(); } catch (SocketTimeoutException e) { // TODO: handle exception Debug.Logger("ERROR: Send Key Socket TimeOut exception..!"); return false; } catch (SocketException e) { // TODO: handle exception Debug.Logger("ERROR: Send Key Socket exception..!"); return false; } catch (IOException e) { // TODO: handle exception Debug.Logger("ERROR: Send Key IO exception..!"); return false;
}
as you see some exceptions shall be catched..
And the crucial method is the checkDisconnection() after sending data.
public static boolean checkDisconnection() throws IOException { // Set socket timeout value to TIME_FOR_SOCKET_REACHABLE rc_sock.setSoTimeout(TIME_FOR_SOCKET_REACHABLE); // 1000ms DataInputStream is = new DataInputStream(rc_sock.getInputStream()); Debug.Logger(" write to sock avail : " + is.available() + " reachable: " \ + rc_sock.getInetAddress().isReachable(TIME_FOR_SOCKET_REACHABLE));
if(rc_sock.getInetAddress().isReachable(TIME_FOR_SOCKET_REACHABLE)) { byte[] receiveBuffer = new byte[1024]; int bytesRead = is.read(receiveBuffer, 0, 1024); Debug.Logger(" write to sock : " + bytesRead); if(bytesRead == -1){ throw new IOException("byteRead = -1, Connection closed."); } } else { return false; } return true; }
It checks availability of socket for a given time of “TIME_FOR_SOCKET_REACHABLE” and reads the buffer simultanously. Of cource this method could be set as a thread that checks for every 1-2 seconds like HeartBeat function.
This works for me to check sudden disconnection between server and client sides at real time. Hope to help you as well..
Program everything.