通过SocketChannel传输文件时丢失字节

时间:2014-07-03 07:06:41

标签: java nio filechannel

我正在使用nio ServerSocketChannel和SocketChannel在客户端和服务器之间传输大文件。问题是当我将大小为6060064字节的文件从发送方传输到接收方时,接收方只收到6059040字节丢失了一些字节。作为文件大小变得越大,缺失字节的差异越大。我找不到为什么这些字节丢失。

发件人代码:

public boolean send(SelectionKey selectionKey) {

    File file = new File("/media/data1/sample.mp4");
    try {
        SocketChannel socketChannel = (SocketChannel) selectionKey
                .channel();
        FileInputStream fileInputStream = new FileInputStream(file);
        System.out.println("File Length :: " + file.length());
        System.out.println("File lastModified :: " + file.lastModified());

        FileChannel fileChannel = fileInputStream.getChannel();

        transfer(fileChannel, socketChannel, file.length(), 1024 * 50);

        fileInputStream.close();

        System.out.println("File Send Completely Done 100%....");
        System.out.println("Closing Connection 100%....");

        return true;

    } catch (Exception e) {
        System.out.println(e);
        System.out.println("Connection Failed. Connectiontimeout.");
        return false;
    }
}

public static void transfer(FileChannel fileChannel,
        SocketChannel socketChannel, long lengthInBytes,
        long chunckSizeInBytes)
        throws IOException {

    long overallBytesTransfered = 0L;
    long time = -System.currentTimeMillis();

    while (overallBytesTransfered < lengthInBytes) {

        long bytesTransfered = 0L;

        bytesTransfered = fileChannel.transferTo(
                overallBytesTransfered,
                Math.min(chunckSizeInBytes, lengthInBytes
                        - overallBytesTransfered), socketChannel);

        System.out.println("bytesTransfered :: " + bytesTransfered);

        overallBytesTransfered += bytesTransfered;

        System.out.printf(
                "overall bytes transfered: %s progress %s%%\n",
                overallBytesTransfered, Math.round(overallBytesTransfered / ((double) lengthInBytes) * 100.0));
    }

    time += System.currentTimeMillis();

    System.out.printf("Transfered: %s bytes in: %s s -> %s kbytes/s\n",
                overallBytesTransfered, time / 1000,
                (overallBytesTransfered / 1024.0) / (time / 1000.0));
    System.out.println("------- File transfer completed ------");

}

接收者代码:

public boolean recieve(SelectionKey key) {
    SocketChannel socketChannel = null;
    Socket socket = null;

    try {
        socketChannel = (SocketChannel) key.channel();
        socket = socketChannel.socket();
        System.out.println(socketChannel.getRemoteAddress());

        // Save file destination
        String FileKey = "/media/data1/Test/sample1.mp4";
        // File size
        long sizeInBytes = 6060064;

        long timeStap = 1402301850000l;

        File file = new File(FileKey);
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        FileChannel fileChannel = fileOutputStream.getChannel();

        transfer(fileChannel, socketChannel, sizeInBytes, 1024 * 100);

        fileOutputStream.close();

        file.setLastModified(timeStap);
        socket.close();
        return true;

    } catch (Exception e) {
        System.out.println("Connection Failed. Connectiontimeout.");
        e.printStackTrace();
        return false;
    }
}

public static void transfer(FileChannel fileChannel,
        SocketChannel socketChannel, long lengthInBytes, long chunckSizeInBytes)
        throws IOException {

    long overallBytesTransfered = 0L;
    long time = -System.currentTimeMillis();
    while (overallBytesTransfered < lengthInBytes) {

        long bytesTransfered = 0L;

        bytesTransfered = fileChannel.transferFrom(
                socketChannel,
                overallBytesTransfered,
                Math.min(chunckSizeInBytes, lengthInBytes
                        - overallBytesTransfered));

        System.out.println("bytesTransfered :: " + bytesTransfered);

        overallBytesTransfered += bytesTransfered;

        System.out.printf(
                "overall bytes transfered: %s progress %s%%\n", overallBytesTransfered,
                Math.round(overallBytesTransfered / ((double) lengthInBytes) * 100.0));

    }

    time += System.currentTimeMillis();

        System.out.printf("Transfered: %s bytes in: %s s -> %s kbytes/s\n",
                overallBytesTransfered, time / 1000,
                (overallBytesTransfered / 1024.0) / (time / 1000.0));
        System.out.println("-------Dateiübertragung fertig------");

}

发件人输出:

  

bytesTransfered :: 18464

     

转移的总字节数:6060064进度100%

     

转移:6060064字节:119秒 - &gt; 49.67708595651809千字节/秒

接收者输出:

  

bytesTransfered :: 0

     

转移的总字节数:6059040进度100%

接收器的while循环继续,直到我手动停止进程, bytesTransfered 总是在接收器端返回零,而文件大小增加到6059040字节。

任何人都可以告诉为什么这些字节丢失了。

1 个答案:

答案 0 :(得分:-2)

我们在JDK7u60上看到了同样的事情(之前我们没有看到

我们注意到,如果缓冲区大于200KB,则SocketChannel在接收器有时间读取套接字之前关闭。

到目前为止,我们唯一的建议是用暂停来限制写入

int bytes = socketChannel.write(currentWriteBuffer);
if (bytes > 200000) {
    try {
        Thread.sleep(100 * (bytes / 200000));
    }
    catch (InterruptedException e) {
      // ignore 
    }
}

我尚未调查实际限制或实际延迟,但这对我们有用。 请注意,我在研究更好的答案时发现了你的问题。