尝试传输文件时套接字关闭异常

时间:2017-12-04 20:03:32

标签: java sockets networking tcp

我正在尝试使用Java和TCP将文件从服务器传输到客户端,但是在客户端我得到一个套接字关闭异常,而服务器在尝试传输文件时没有错误。我对此错误感到困惑,因为在尝试从中读取之前我没有关闭套接字。服务器接受连接并发送文件,但客户端会收到该错误。有什么建议吗?

错误是:

  

java.net.SocketException:Socket关闭

服务器线程的运行功能:

public void run() {
    System.out.println("Service thread running for client at " + socket.getInetAddress() + " on port " + socket.getPort());
    try {
        File file = new File("hank.txt");
        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(fis);
        OutputStream os = socket.getOutputStream();

        byte[] contents;
        long fileLength = file.length();
        long current = 0;

        long start = System.nanoTime();
        while(current!=fileLength) {
            int size = 1000;
            if(fileLength - current >= size) {
                current += size;
            }
            else {
                size = (int)(fileLength - current);
                current = fileLength;
            }
            contents = new byte[size];
            bis.read(contents,0,size);
            os.write(contents);
            System.out.println("sending file..." + (current*100)/fileLength+"% complete!");
        }
        os.flush();
        this.socket.close();
    }catch(Exception e) {
        e.printStackTrace();
    }
}

客户收到文件代码:

    System.out.println("Going to get the file...");
    socket = new Socket(response.getIP().substring(1), response.getPort());

    byte[] contents = new byte[10000];
    FileOutputStream fos = new FileOutputStream("hank.txt");
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    InputStream in = socket.getInputStream();

    int bytesRead = 0;
    System.out.println("Starting to read file...");
    while((bytesRead = is.read(contents))!=-1) { //the error points to this lin
        bos.write(contents,0,bytesRead);
    }

    bos.flush();
    bos.close();
    in.close();

    //
    socket.close();

1 个答案:

答案 0 :(得分:1)

此套接字的输入流可在变量

中使用
InputStream in = socket.getInputStream();

所以

 Change is.read(contents)) to in.read(contents))