title: DataInputStream giving java.io.EOFException
body: <p>I have created small CLI client-server application. Once the server is loaded the client can connect to it and send commands to the server.</p>
  
  <p>The first command is to get list of files that server is loaded with.</p>
  
  <p>Once the socket connection is established. I request user to enter a command.</p>
  
  <p>ClientApp.java</p>
  
  <pre><code>Socket client = new Socket(serverName, serverPort); 
  
  Console c = System.console();
  if (c == null) {
      System.err.println("No console!");
      System.exit(1);
  }
  
  String command = c.readLine("Enter a command: ");
  
  OutputStream outToServer = client.getOutputStream();
  DataOutputStream out = new DataOutputStream(outToServer);
  out.writeUTF(command);  
  </code></pre>
  
  <p>Then the server capture user's command and send appropriate replies. </p>
  
  <p>SeverApp.java -</p>
  
  <pre><code>Socket server = serverSocket.accept();
  DataInputStream in = new DataInputStream(server.getInputStream());
  
  switch (in.readUTF()){
      case "list":
          for (String fileName : files) {
              out.writeUTF(fileName);
          }
          out.flush();
  
  }
  server.close();
  </code></pre>
  
  <p>Next the client retrieve server's response -</p>
  
  <p>ClientApp.java</p>
  
  <pre><code>InputStream inFromServer = client.getInputStream();
  DataInputStream in = new DataInputStream(inFromServer);
  String value;
  while((value = in.readUTF()) != null) {
      System.out.println(value);
  }
  
  client.close();
  </code></pre>
  
  <p><code>files</code> is a ArrayList which i keep list of files loaded to the sever.  When client sends <code>list</code> command to the sever, i need to send array of strings (list of file names) back. Similarly app will have more commands.</p>
  
  <p>Now when i do such request i get list of files and trows <code>java.io.EOFException</code> from <code>while((value = in.readUTF()) != null) {</code></p>
  
  <p>How to fix this ?</p>
  
  <hr>
  
  <p>EDIT (SOLUTION) ---</p>
  
  <p><a href="http://docs.oracle.com/javase/tutorial/essential/io/datastreams.html" rel="nofollow">http://docs.oracle.com/javase/tutorial/essential/io/datastreams.html</a></p>
  
  <p>Notice that DataStreams detects an end-of-file condition by catching EOFException, instead of testing for an invalid return value. All implementations of DataInput methods use EOFException instead of return values.</p>
  
  <pre><code>try {
      while (true) {
          System.out.println(in.readUTF());
      }
      } catch (EOFException e) {
  }
  </code></pre>