DataInputStream给出了java.io.EOFException

我创建了小型CLI客户端 – 服务器应用程序。 加载服务器后,客户端可以连接到服务器并将命令发送到服务器。

第一个命令是获取服务器加载的文件列表。

一旦建立套接字连接。 我请求用户输入命令。

ClientApp.java

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); 

然后服务器捕获用户的命令并发送相应的回复。

SeverApp.java –

 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(); 

接下来客户端检索服务器的响应 –

ClientApp.java

 InputStream inFromServer = client.getInputStream(); DataInputStream in = new DataInputStream(inFromServer); String value; while((value = in.readUTF()) != null) { System.out.println(value); } client.close(); 

files是一个ArrayList,我保留加载到服务器的文件列表。 当客户端向服务器发送list命令时,我需要发回字符串数组(文件名列表)。 同样,app会有更多命令。

现在,当我做这样的请求时,我得到文件列表并从while((value = in.readUTF()) != null) { trows java.io.EOFException

如何解决这个问题?


编辑(解决方案)—

http://docs.oracle.com/javase/tutorial/essential/io/datastreams.html

请注意,DataStreams通过捕获EOFException来检测文件结束条件,而不是测试无效的返回值。 DataInput方法的所有实现都使用EOFException而不是返回值。

 try { while (true) { System.out.println(in.readUTF()); } } catch (EOFException e) { } 

readUTF方法永远不会返回null。 相反,你应该这样做:

 while(in.available()>0) { String value = in.readUTF(); 

查看javadocs,如果此输入流在读取所有字节之前到达结尾,则抛出EOFException。

使用FilterInputStream.available() 。

 InputStream inFromServer = client.getInputStream(); DataInputStream in = new DataInputStream(inFromServer); String value; while(in.available() > 0 && (value = in.readUTF()) != null) { System.out.println(value); } ... 

http://docs.oracle.com/javase/tutorial/essential/io/datastreams.html

请注意,DataStreams通过捕获EOFException来检测文件结束条件,而不是测试无效的返回值。 DataInput方法的所有实现都使用EOFException而不是返回值。

 try { while (true) { System.out.println(in.readUTF()); } } catch (EOFException e) { }