title: TCP detect disconnected server from client
body: <p>I'm writing a simple TCP client/server program pair in Java, and the server must disconnect if the client hasn't sent anything in 10 seconds.  socket.setSoTimeout() gets me that, and the server disconnects just fine. The problem is - how can I get the client to determine if the server is closed? Currently I'm using DataOutputStream for writing to the server, and some answers here on SO suggest that writing to a closed socket will throw an IOException, but that doesn't happen.</p>
  
  <p>What kind of writer object should I use to send arbitrary byte blocks to the server, that would throw an exception or otherwise indicate that the connection has been closed remotely?</p>
  
  <p>Edit: here's the client code. This is a test function that reads one file from the file system and sends it to the server. It sends it in chunks, and pauses for some time between each chunk. </p>
  
  <pre><code>public static void sendFileWithTimeout(String file, String address, int dataPacketSize, int timeout) {
      Socket connectionToServer = null;
      DataOutputStream outStream = null;
      FileInputStream inStream = null;
      try {
          connectionToServer = new Socket(address, 2233);
  
          outStream = new DataOutputStream(connectionToServer.getOutputStream());
  
          Path fileObject = Paths.get(file);
  
          outStream.writeUTF(fileObject.getFileName().toString());
  
          byte[] data = new byte[dataPacketSize];
  
          inStream = new FileInputStream(fileObject.toFile());
          boolean fileFinished = false;
          while (!fileFinished) {
              int bytesRead = inStream.read(data);
              if (bytesRead == -1) {
                  fileFinished = true;
              } else {
                  outStream.write(data, 0, bytesRead);
                  System.out.println("Thread " + Thread.currentThread().getName() + " wrote " + bytesRead + " bytes.");
                  Thread.sleep(timeout);
              }
          }
  
      } catch (IOException | InterruptedException e) {
          System.out.println("Something something.");
          throw new RuntimeException("Problem sending data to server.", e);
      } finally {
          TCPUtil.silentCloseObject(inStream);
          TCPUtil.silentCloseObject(outStream);
          TCPUtil.silentCloseObject(connectionToServer);
      }
  }
  </code></pre>
  
  <p>I'd expect the outStream.write to throw an IOException when it tries to write to a closed server, but nothing. </p>