title: Java NIO TCP timeout issue
body: <p>I am using one SocketChannel in 2 threads, one thread for sending the data and another for receiving the data.</p>
  
  <pre><code>SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress(ip,port));
  socketChannel.configureBlocking(false);
  </code></pre>
  
  <p>Thread 1: uses the above socketchannel to write the data</p>
  
  <p>Thread 2: uses the same socketchannel to read the data</p>
  
  <p>I am not using any selectors with the socketchannel as I need the write and read to be asynchronous (using 2 different threads)</p>
  
  <p>PROBLEM: When the connection is lost, the socketchannel.write() and socketchannel.read() operation does not throw any error. It just blocks the operation.</p>
  
  <p>I need to detect the connection loss.</p>
  
  <p>I tried using the heartbeat method in Thread 2 but because the read operation just blocks, this method did not work. Is there any other way to detect the connection loss without using the heartbeat in a new Thread?</p>
  
  <p>Is it possible to throw error while writing/reading if there is connection loss?</p>
  
  <p>Thanks in advance.</p>
  
  <p>EDIT:</p>
  
  <p>Thread 1: </p>
  
  <pre><code>public void run() {
    socketChannel = SendAndReceivePacketUtil.createConnection(ip, port);
    socketChannel.configureBlocking(false);
  
    RecTask task = new RecTask(socketChannel);
    Thread recThread = new Thread(task);
    recThread.start();
  
    while(true)
    {
       byte[] data= getDataFromQueue(ip);
       if(data!= null) {
           //print(new String(data));
           sendPacket(data, socketChannel);
       }
     }
  }
  </code></pre>
  
  <p>Thread 2: (RecTask)</p>
  
  <pre><code>public void run() {
    while(true) {
      byte[] data = receivePacket(socketChannel);
      //print(new String(data));
    }
  }
  </code></pre>
  
  <p>Both Thread 1 &amp; 2 have try-catch-finally blocks. finally closes the socketchannel.</p>
  
  <p>sendPacket: </p>
  
  <pre><code>int dataSent = 0;
  while (dataSent &lt; data.length) {
      long n = socketChannel.write(buf);
          if (n &lt; 0) {
              throw new Exception();
          }
          dataSent += (int) n;
   }
  </code></pre>
  
  <p>receivePacket: </p>
  
  <pre><code>int dataRec = 0;
  byte[] data = new byte[length];
  ByteBuffer buffer = ByteBuffer.wrap(data);
  
  while (dataRec &lt; length) {
      long n = socketChannel.read(buffer);
      if (n &lt; 0) {
          throw new Exception();
      }
      dataRec += (int) n;
  }       
  return data;
  </code></pre>
  
  <p>I send and receive data continuously. But as soon as the connection is lost, nothing prints and the code just gets stuck. Its an android wifi direct application. For connection loss scenario I just switch off the wifi module.</p>