Я разрабатываю простую программу для переноса файлов между клиентом и сервером. Вот мой код: Мой клиент (Sender):EOFException или SocketException: Socket закрыт, когда файл передачи через сокет
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){}
}
}
Я хочу Tranfer более одного файла, так что я не хочу закрыть розетку. Таким образом, я использую переменную «len», чтобы проверить, что файл полностью переведен.
Если я закрываю «вывод» после отправки файла, тогда сервер thows EOFException и файл отправляется успешно.
Когда я не закрываю вывод, сервер не может получить успех файла. Но сервер не выбрасывает EOFException.
Помогите решить эту проблему? Update: Вот мой вывод на экран консоли, если я не закрываю переменную "выход" на клиенте:
Pos: 496
Спасибо. Извините за мой плохой английский
Как именно сервер не получает файл успешно, если вы не закрываете сокет? Застрял ли он в цикле? –
Ваше имя неверное. EOFException и «socket is closed» - это два отдельных условия, а не один. – EJP