这个问题在这里已有答案:
我有一个客户端和服务器程序应该像这样工作:客户端在命令行(stdin)中输入文件名,服务器通过套接字向客户端发送文件数据 . 发送另一个名称和另一个文件的客户端类型 .
但是,我目前只能发送一个文件 . 我第二次输入文件名,它不会进入我的客户端的while循环:“while((count = in.read(buffer))> 0){”
客户端(变量“fromUser”是服务器所请求文件的文件名,outCommands是将此文件名传输到服务器的传出数据流):
while(true) {
fromUser = stdIn.readLine();
if (fromUser != null) {
outCommands.println(fromUser);
while ((count = in.read(buffer)) > 0) {
String fileName = "downloaded" + in.readUTF();
OutputStream fileOut = new FileOutputStream(fileName);
try
{
fileOut.write(buffer, 0, count);
fileOut.flush();
} catch (IOException e) {
}
fileOut.close();
break;
}
} else if (fromUser.equals("Stop")) {
in.close();
stdIn.close();
dlSocket.close();
}
}
服务器(“dlp”是服务器套接字,“out”是传出数据流):
while(!(fileD = in.readLine()).equals(null)) {
System.out.println("Line read:" + fileD);
// Load file
File file = new File(fileD);
System.out.println(file.getAbsolutePath());
System.out.println("File created...");
InputStream fileIn = new FileInputStream(file);
outputLine = dlp.processInput(null);
byte[] buffer = new byte[8192];
int count;
while ((count = fileIn.read(buffer)) > 0) {
System.out.println("Beginning file transfer");
out.write(buffer, 0, count);
}
System.out.println("Completed file transfer");
// Write filename to out socket
out.writeUTF(file.getName());
out.writeLong(file.length());
out.flush();
}
in.close();
out.close();
clientSocket.close();
有人可以帮我弄清楚为什么会这样吗?我不明白为什么一旦服务器在客户端请求之后发送第二个文件,“count = in.read(buffer)”不大于零 .
Src:https://github.com/richardrl/downloader/tree/master/src/main/java
1 回答
因为你在while循环中使用了
break
它会中断并且不会返回到循环条件 . 而不是break
你应该使用continue
- 甚至更好,删除它,因为它在循环范围的末尾是不必要的(无论如何都要重新迭代):当使用
continue
执行行时,循环停止,下一行要执行循环条件 . 如上所述,无论如何都不会重新迭代 .