2 つのプログラムを実装しています。クライアントとサーバー。クライアントはサーバーからローカル ファイル システムにダウンロードするファイルを要求します。
1 つのファイルをダウンロードした後、クライアントは必要に応じて別のファイルをダウンロードできる必要があります。
ただし、ファイルをダウンロードした後、サーバーから例外が表示されます
java.net.SocketException: Socket closed
これが私のコードです..
クライアント:
byte[] aByte = new byte[0];
int bytesRead;
String msg;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
while (!(msg = input.readLine()).equals("end")) {
String myFolderName = "ServerFolder";
File folder=new File(myFolderName);
if (!folder.exists()){
folder.mkdir();
}
System.out.println("file downloading");
try {
System.out.println("1");
fos = new FileOutputStream("ServerFolder/"+fileToDownload);
bos = new BufferedOutputStream(fos);
System.out.println("MSG: "+msg);
bytesRead = in.read(aByte, 0, aByte.length);
System.out.println("2");
do {
baos.write(aByte);
bytesRead = in.read(aByte);
} while (bytesRead != -1);
System.out.println("3");
bos.write(baos.toByteArray());
bos.flush();
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
bos.close();
} catch (IOException ex) {
System.err.println(ex);
}
サーバ:
if (outToClient != null) {
System.out.println("2");
File myFile = new File(msg);
byte[] mybytearray = new byte[(int) myFile.length()];
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException ex) {
// Do exception handling
}
System.out.println("3");
bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
System.out.println("mybytearray.length: "+(int) myFile.length());
out.write((int) myFile.length()+"\r\n");
out.write("end\r\n");
out.flush();
outToClient.write(mybytearray, 0, mybytearray.length);
outToClient.flush();
s.shutdownOutput();
outToClient.close();
System.out.println("4");
} catch (IOException ex) {
System.out.println("5");
System.err.println(ex);
}
(すべての接続は各メソッドの最初で行われます)
私が持っていた
s.close();
サーバー内ですが、エラーが発生した場合に備えて削除しましたが、そうではありません..
私はそれを推測しています
outToClient.close();
も原因ではないでしょうか? ...
また、私はこの問題をグーグルで検索し、サーバーがファイルを送信する前にクライアントにファイルのサイズを伝えることを提案した人もいました..しかし、それもうまくいきませんでした..その部分も削除しました(または間違っていたのかもしれません) ..)
ありがとう:)