我正在使用java进行文件传输线程
这是服务器代码
(fileWriter = new BufferedOutputStream(fileTransferSocket.getOutputStream()))
try {
BufferedInputStream fileReader = new BufferedInputStream(new FileInputStream(CLIENT_PATH + "/" + filename));
int packet;
while((packet = fileReader.read()) != -1)
fileWriter.write(packet);
fileWriter.flush();
fileReader.close();
System.out.println(filename + " send complete");
}
客户代码
(fileReader = new BufferedInputStream(fileTransferSocket.getInputStream()))
try {
BufferedOutputStream fileWriter = new BufferedOutputStream(new FileOutputStream(new File(PROGRAM_PATH + "/" + filename)));
int packet;
while((packet = fileReader.read()) != -1)
fileWriter.write(packet);
System.out.println(filename + " receive complete.");
fileWriter.close();
}
服务器打印
System.out.println(filename + " send complete");
这意味着服务器发送文件的每个字节。
但是,客户端无法打印
System.out.println(filename + " receive complete.");
我检查了循环运行的次数(Checked Both,服务器和客户端)
while while循环运行685次
我认为Client的while循环无法识别文件传输结束。
任何人都知道问题?
答案 0 :(得分:1)
要将EOF
发送到套接字,请关闭服务器上的fileWriter
。
while((packet = fileReader.read()) != -1)
fileWriter.write(packet);
fileWriter.close(); // note
fileReader.close();
答案 1 :(得分:-1)
您可以在服务中测试print -1以告知转换的结束:
while((packet = fileReader.read()) != -1)
fileWriter.write(packet);
fileWriter.write(-1);