我创建了小型 CLI 客户端-服务器应用程序。加载服务器后,客户端可以连接到它并向服务器发送命令。
第一个命令是获取服务器加载的文件列表。
一旦套接字连接建立。我请求用户输入命令。
客户端应用程序.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);
然后服务器捕获用户的命令并发送适当的回复。
服务器应用程序.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();
接下来客户端检索服务器的响应-
客户端应用程序.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
命令时,我需要发回字符串数组(文件名列表)。同样,应用程序将有更多命令。
现在,当我执行此类请求时,我会从 while((value = in.readUTF()) != null) {
如何解决这个问题?
编辑(解决方案)---
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。
关于java - DataInputStream 给出 java.io.EOFException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23064917/