Skip to content

Windows 下使用 transferTo 实现文件发送的问题 #1

@maizhenhui

Description

@maizhenhui

public static void client2() throws Exception{
long start = System.currentTimeMillis();
SocketChannel socketChannel = SocketChannel.open( new InetSocketAddress( "127.0.0.1" ,8888) );
FileChannel inFileChannel = FileChannel.open(Paths.get("D:/mvnrep.rar"), StandardOpenOption.READ);
//使用直接缓冲区(零拷贝)
inFileChannel.transferTo(0, inFileChannel.size() ,socketChannel ) ; // a transferFrom/transferTo b
long end = System.currentTimeMillis();
System.out.println("直接缓冲区方式(客户端)发送文件:"+(end-start));
inFileChannel.close();
socketChannel.close();
}

可能由于 Windows 底层对于网络传输的一些限制,经测试,一次大约只能发送 8MB 的数据
需要进行多次发送:

public class Client {
    public static void main(String[] args) {
        // 打开通道时指定 连接的 目标(服务端的 IP与端口号)
        try(SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("localhost",8888));
            FileChannel inFileChannel = FileChannel.open(Paths.get("e://input.rar"));) {
            // 性能计时
            long start = System.currentTimeMillis();
            // 使用零拷贝,打通 inFileChannel 与 socketChannel 之间的通道
            //Linux
            // inFileChannel.transferTo(0,inFileChannel.size(),socketChannel);
            // Windows
            // 由于 Windows 底层限制,需要多次进行发送
            long transferByte = 0;
            long totalByte = 0;
            while (totalByte < inFileChannel.size()){
                transferByte = inFileChannel.transferTo(totalByte,inFileChannel.size()-transferByte,socketChannel);
                System.out.println("持续发送。。。");
                totalByte += transferByte;
            }
            System.out.println("总共发送:"+totalByte);

            System.out.println("花费时间:"+(System.currentTimeMillis() - start));
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions