title: Detecting Socket Disconnect Using TCP KeepAlive
body: <p>I'm developing a server that hosts 3rd party devices over TCP/IP and have been experiencing sudden connection drops (the devices are connecting via cellular).  I need to find a way to detect a disconnect without having to write data to the device itself.</p>
  
  <p>I've looked at using the TCP keepalive functionality but Java doesn't appear to allow any adjustment of the timing of the keepalive operations.</p>
  
  <p>Is there any suggested method for doing this?</p>
  
  <p>My simplified socket code is as follows: </p>
  
  <pre><code>public class Test2Socket {
      public static void main(String[] args) {
          try {
              ServerSocket skt = new ServerSocket(1111);
  
              Socket clientSocket = skt.accept();
  
              clientSocket.setKeepAlive(true);
  
              System.out.println("Connected..");
  
              BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
  
              String inputLine;
  
              while((inputLine = input.readLine()) != null)
              {
                  System.out.println(inputLine);
              }
  
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
  }
  </code></pre>
  
  <p>Any feedback would be greatly appreciated.</p>