我正在开发客户端和服务器之间的简单文件传输应用程序。 这里是我的代码: 我的客户(发件人):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