我正在開發客戶端和服務器之間的簡單文件傳輸應用程序。 這裏是我的代碼: 我的客戶(發件人):EOFException或SocketException:在通過套接字傳輸文件時關閉套接字
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。
你能幫我解決這個問題嗎? 更新:這是我在控制檯屏幕上輸出,如果我不關閉變量 「輸出」 在客戶端:
POS:496和
感謝。 對不起,我可憐的英語
如果您沒有關閉套接字,服務器如何不成功接收文件?它會卡在循環中嗎? –
您的標題有誤導性。 EOFException和'socket is closed'是兩個單獨的條件,而不是一個。 – EJP