嗨,我正在尝试学习如何通过套接字发送文件,所以我编写了两个非常简单的 java 类,客户端和服务器,它们在这里
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main (String[] args)throws IOException{
File f = new File("J:\\RepServer\\zebi.txt");
if(!f.exists()){
f.createNewFile();
}
//System.out.print(f.exists()+f.getName());
ServerSocket ss = new ServerSocket(1000);
Socket s = ss.accept();
FileInputStream fileStream = new FileInputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
oos.writeObject("Envoi Fichier|"+f.getName()+"|"+f.length());
byte[] buffer = new byte[150000];
long completed =0;
while(completed <= f.length()){
fileStream.read(buffer);
oos.write(buffer);
completed += 150000;
}
oos.writeObject("Envoi termine");
fileStream.close();
}
}
和客户端类
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
public class Client {
/**
* @param args
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws IOException, ClassNotFoundException {
new File("J:\\RepClient\\").mkdir();
Socket s = new Socket("127.0.0.1",1000);
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
String fileName = ((String)ois.readObject()).split("|")[1].trim();
FileOutputStream fos = new FileOutputStream("J:\\RepClient\\"+fileName);
byte[] buffer = new byte[200000];
int byteLus = 0, compteur = 0;
while(byteLus >= 0){
byteLus = ois.read();
if(byteLus >= 0){
fos.write(buffer, 0, byteLus);
compteur += byteLus;
System.out.println("Le nombre de bytes lus est :"+byteLus);
}
if(byteLus < 1024){
fos.flush();
break;
}
}
}
}
所以我启动服务器,然后启动客户端,服务器将文件发送到客户端,客户端创建文件但为空,因为在服务器可以写入之前发生此异常。
Exception in thread "main" java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(Unknown Source)
at java.net.SocketOutputStream.write(Unknown Source)
at java.io.ObjectOutputStream$BlockDataOutputStream.writeBlockHeader(Unknown Source)
at java.io.ObjectOutputStream$BlockDataOutputStream.write(Unknown Source)
at java.io.ObjectOutputStream.write(Unknown Source)
at Server.main(Server.java:25)
问题是我没有关闭客户端中的任何套接字或流。那么为什么连接关闭了?顺便说一句,冲洗在做什么?