使用SocketException发送大文件(~1GB)失败

时间:2013-05-23 17:37:09

标签: java sockets networking large-files file-handling

我正在尝试使用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();
        }
    }
}

Reciever

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();
        }
    }
}

1 个答案:

答案 0 :(得分:2)

if(n<(8192)){
    fos.close();
    bis.close();

这意味着如果您获得的内容少于预期的字节数,那么您将关闭套接字。没有理由这样做。