1

我创建了小型 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);  

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

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

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

客户端应用程序.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服务器发送命令时,我需要发送回字符串数组(文件名列表)。同样的应用程序将有更多的命令。

现在,当我提出这样的请求时,我会java.io.EOFExceptionwhile((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) {
}
4

3 回答 3

3

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

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

查看 javadocs,如果此输入流在读取所有字节之前到达末尾,则会引发 EOFException。

于 2014-04-14T16:13:58.490 回答
1

使用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);
}

...
于 2014-04-14T16:12:12.703 回答
0

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) {
}
于 2014-04-16T06:42:41.760 回答