java.io.EOFException:在java.io.DataInputStream.readUTF(未知源)处,



我制作了一个简单的服务器客户端应用程序,从服务器逐行读取文件,并逐行写入客户端的新文件。应用程序正确地写入文件中的行,但当文件到达末尾时,我发现了以下错误:

java.io.EOFException
at java.io.DataInputStream.readUnsignedShort(Unknown Source)
at java.io.DataInputStream.readUTF(Unknown Source)
at java.io.DataInputStream.readUTF(Unknown Source)
at it.sendfile.socket.FileClient1.main(FileClient1.java:19)

我的代码:

public class FileServer1 {
public static void main(String[] args) {
int port = 3000;
// open server socket
ServerSocket ss = null;
try {
ss = new ServerSocket(port);
Socket s = ss.accept();
DataOutputStream outToClient = new DataOutputStream(s.getOutputStream());
File testFile = new File("C:\temp\tmpbgoutcoge");
BufferedReader input = new BufferedReader(new FileReader(testFile));
String line;
while ((line = input.readLine()) != null) {
outToClient.writeUTF(line);
outToClient.writeUTF("-----------------------------");
outToClient.flush();
Thread.currentThread().sleep(1000);
}
input.close();
outToClient.close();
s.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
public class FileClient1 {
public static void main(String[] args) {
try (PrintWriter out = new PrintWriter(new FileWriter("C:\temp\tmpbgoutcoge1.txt", true));) {
Socket s = new Socket("localhost", 3000);
DataInputStream inFromServer = new DataInputStream(new BufferedInputStream(s.getInputStream()));
while (true) {
String line = inFromServer.readUTF();
System.out.println(line);
out.write(line);
out.println("n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

当我到达文件末尾时,我必须找到While停止条件,但我已经尝试了(line=inFromServer.readUTF(((!=null,但不起作用。在FileClient1类中,我无法关闭套接字和DataInputStream。一条消息说:";无法访问的代码";。

readUTF((永远不会返回null。您需要在关闭之前发送一个"sentinel值"——一个指示流结束的特殊值。

显然,您希望它是在正常用例中不太可能发送的东西。我建议使用"uffff"(长度为1的字符串(,因为U+FFFF保证不是定义的字符。

您可以使用

while(inFromServer.available()>0) {  
String line = inFromServer.readUTF();
System.out.println(line);
out.write(line);
out.println("n");
}  

而不是

while (true) {
String line = inFromServer.readUTF();
System.out.println(line);
out.write(line);
out.println("n");
}

相关内容

最新更新