我正在尝试使用 java 中的套接字编程为 p2p 文件共享应用程序发送大文件。此代码发送 200-300 mb 文件没有任何问题,但对于 1 gb 左右的大文件,它会给出错误:-
java.net.SocketException: Software caused connection abort: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
at java.io.BufferedOutputStream.write(BufferedOutputStream.java:105)
at FileSender.main(FileSender.java:28)
正如我得到的许多答案中所建议的那样,我已经在小块发送文件。我应该怎么做才能发送 1 GB 的文件。我在 Windows 上编程。
这是我的代码:
服务器
public class FileSender {
public static void main(String...s)
{
BufferedOutputStream bos;
String file="D:\\filename.mp4";
try {
ServerSocket sock=new ServerSocket(12345);
while(true)
{
System.out.println("waiting");
Socket soc=sock.accept();
bos= new BufferedOutputStream(soc.getOutputStream());
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
int n=-1;
byte[] buffer = new byte[8192];
while((n = bis.read(buffer))>-1)
{
bos.write(buffer,0,n);
System.out.println("bytes="+n);
bos.flush();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
接收者
public class FileReciev {
public static void main(String...s)
{
try
{
Socket sock=new Socket("127.0.0.1",12345);
File file=new File("D:\\newfilename.mp4");
BufferedInputStream bis=new BufferedInputStream(sock.getInputStream());
FileOutputStream fos = new FileOutputStream(file);
int n;
byte[] buffer = new byte[8192];
System.out.println("Connected");
while ((n = bis.read(buffer)) > -1) {
System.out.println("bytes="+n);
fos.write(buffer, 0, n);
if(n<(8192)){
fos.close();
bis.close();
break;
}
fos.flush();
}
System.out.println("recieved");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}