私はこのように動作するはずのクライアントとサーバープログラムを持っています: クライアントはコマンドライン(stdin)にファイル名を入力し、クライアントはファイルデータをソケット。 別の名前のクライアントタイプと別のファイルが送信されます。複数のファイルを一度に1つずつ送信するJava
ただし、現在のところ、1つのファイルのみを送信できます。 2回目にファイル名を入力すると、クライアントの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」はサーバソケットで、「アウト」は、送信データストリームです) :
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();
なぜこのようなことが起こっているのか理解できますか?クライアントが要求した後にサーバーが2番目のファイルを送信すると、なぜ "count = in.read(buffer)"がゼロより大きくないのか分かりません。
のSrc:https://github.com/richardrl/downloader/tree/master/src/main/java
休憩は問題ではありませんhttp://stackoverflow.com/questions/12393231/break-statement-inside-two-while-loops –
このコードには、ファイル全体が読み込まれるという前提で多くの問題があります正確に1つの読み込みで、長さを書き込んだり読んだりしないようにしたり、ファイルの後にファイル名と長さを書き込んだりする必要があります。私の答えを複製に見てください。 – EJP
特に、 'count = in.read(buffer)'は、最初のファイルの後にストリームの終わりに達したら、決してゼロ以外になることはありません。そのため、ファイルが送信される前の長さを知る必要があるので、読み込むバイト数を知る必要があります。このコードは2番目の 'readUTF()'に 'EOFException'を投げます。 – EJP