クライアントとサーバー間の単純なファイル転送アプリを開発しています。ここに私のコードがあります:私のクライアント(送信者):
try{
File file_sender=XMLParser.register(peername, address, port, listfile);
int count;
byte[] buffer = new byte[1024];
int len=(int) file_sender.length();
byte[] mybytearray = new byte[len];
DataOutputStream output=new DataOutputStream(Info.connection.getOutputStream());
output.writeInt(len);
System.out.println(len);
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(file_sender));
bis.read(mybytearray, 0, len);
output.write(mybytearray, 0, len);
bis.close();
output.close();
// Info.connection.close();
}catch(Exception ex){
System.out.println(ex.toString());
}
私のサーバー(レシーバー):
public class IOThread extends Thread {
private Socket connection;
private DataInputStream input;
public IOThread(Socket connection) throws IOException{
this.connection=connection;
input=new DataInputStream(connection.getInputStream());
}
@Override
public void run(){
while(true){
try{
int filesize=12022386;
int bytesRead;
int currentTot = 0;
byte[] bytearray = new byte [filesize];
int len=input.readInt();
FileOutputStream fos = new FileOutputStream("data.xml");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead=input.read(bytearray, 0,bytearray.length);
System.out.println(len);
currentTot=bytesRead;
do{
bytesRead=input.read(bytearray, currentTot, (bytearray.length-currentTot));
if(bytesRead>=0) currentTot+=bytesRead;
System.out.println("pos: "+currentTot);
} while(len!=currentTot);
bos.write(bytearray, 0, currentTot);
bos.close();
//connection.close();
System.out.println("Done");
}catch(EOFException ex){
System.out.println(ex.toString());
break;
}catch( Exception ex){}
}
}
複数のファイルを転送したいので、ソケットを閉じたくありません。そのため、変数「len」を使用して、ファイルが完全に転送されたことを確認します。
ファイルの送信後に「出力」を閉じると、サーバーは EOFException をスローし、ファイルは正常に送信されます。
出力を閉じないと、サーバーは成功したファイルを受信できません。しかし、サーバーは EOFException をスローしません。
この問題を解決するのを手伝ってもらえますか? 更新:クライアントで変数「出力」を閉じない場合のコンソール画面の出力は次のとおりです。
246
順位: 496
ありがとう。 下手な英語でごめんなさい