title: Java: Socket close connection and ObjectInputStream
body: <p>My code looks like this, this is Server code (<code>Runnable</code>)</p>
  
  <pre><code>public void run() {
      while (true) {
          try {
              System.out.println("Waiting for client...");
              this.socket = serverSocket.accept();
              System.out.println("Client accepted");
              while (true) {
                  readCommand();
                  try {
                      Thread.sleep(2);
                  } catch (Exception e) {
                  }
              }
          } catch (Exception ex) {
              Main.error("Server stopped for current host", ex);
          }
      }
  }
  </code></pre>
  
  <p>My problem is: when the client closes the connection, he still waiting to read the command in <code>readCommand();</code> until a command was sent and an <code>EOFException</code> will be thrown. This is my <code>readCommand</code> method:</p>
  
  <pre><code>private void readCommand() throws Exception {
      Object o = new ObjectInputStream(socket.getInputStream()).readObject();
      if (o instanceof Command) {
          ((Command) o).execute();
          return;
      }
      if (o instanceof Recorder) {
          System.out.println("Recording received");
          ((Recorder) o).executeRecord();
          return;
      }
      if (o instanceof MyKeyEvent) {
          ((MyKeyEvent) o).execute();
          return;
      }
  }
  </code></pre>
  
  <p>So I think before reading it has to check if the connection is open.</p>
  
  <p><strong>Edit:</strong> If I evaluate the <code>run</code>-method code, the <code>EOFException</code> is thrown in the <code>try-catch-body</code>. But he stops accepting clients.</p>