继续通过套接字中断下载

时间:2014-05-29 08:44:02

标签: java sockets

我正在尝试继续从服务器到客户端的中断下载。

发送服务器代码:

long fileLength = file.length();
        String fileName = file.getName();
        int bytesRead = 0;
        long bytesReadAmount = 0;
        byte[] byteArray = new byte[6 * PACKET_SIZE];

        OutputStream outputStream = socket.getOutputStream();

        try {
            BufferedInputStream bufferedIS = new BufferedInputStream(new FileInputStream(file));
            while ((bytesRead = bufferedIS.read(byteArray)) > 0) {
                outputStream.write(byteArray, (int)existingFileSize, bytesRead);
                bytesReadAmount += bytesRead;
                System.out.println("File sending " + fileName + " (send" + bytesReadAmount + " byte, remain " +
                        (fileLength - bytesReadAmount));
            }
            System.out.println("File transfer end");
        } catch (IOException e) {
            System.out.println("File transfer error");
            e.printStackTrace();
        } finally {
            dataOS.flush();
            socket.close();
        }

接收的客户端代码

long bytesReadAmount = 0;
        int bytesRead = 0;
        long size = 0;
        byte[] byteArray = new byte[6 * Server.PACKET_SIZE];

        try {
            File file = new File(DIRECTORY_PATH + fileName);
            file.createNewFile();
            FileOutputStream fileOS = new FileOutputStream(file);
            BufferedOutputStream bufferedOS = new BufferedOutputStream(fileOS);

            while ((bytesRead = dataIS.read(byteArray)) != -1) {
                bufferedOS.write(byteArray, (int)existingFileSize, bytesRead);
                bytesReadAmount += bytesRead;
                System.out.println("File receiving " + fileName + " (" + bytesReadAmount + " bytes received)");
            }
            System.out.println("File " + fileName + " sending OK");
        } catch (IOException e) {
            System.out.println("Connection interrupted");
            e.printStackTrace();
        }
    }

从头到尾发送的大文件效果很好,但是在interrut没有后继续下载(当我试图继续中断文件时发送不工作)。此外,当我发送完整文件时,副本的大小与某些字节的原始大小不同。请帮助解决这个问题

1 个答案:

答案 0 :(得分:2)

offset中使用的write(byteArray, (int)existingFileSize, bytesRead)byteArray中的偏移,而不是原始文件。我建议您在重新启动时使用skip()跳过要读取或写入的数据,并将追加添加到文件中(通过在FileOutputStream构造函数中设置append)