NIO的零拷贝

 测试传输262M视频文件,所需时间约3s

transferTo方法作用:将一个通道的数据传输到另一个通道

参数1:position         从该通道所需传输字节的启示位置

参数2:count        所传字节的长度

参数3:WritableByteChannel        目标通道

    public abstract long transferTo(long position, long count, 
        WritableByteChannel target)throws IOException;

使用案例:

FileInputStream inputFile = new FileInputStream("input.txt");
FileOutputStream outputFile = new FileOutputStream("output.txt");

FileChannel inputChannel = inputFile.getChannel();
FileChannel outputChannel = outputFile.getChannel();

long transferredBytes = inputChannel.transferTo(0, inputChannel.size(), outputChannel);

网络通道传输案例:

 服务端

    public void server1() throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(9527));
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        FileChannel channel = new FileOutputStream("C:\\SwaggerToCL\\test.txt").getChannel();
        while (true) {
            //这玩意没建立连接会堵塞喔,直到有连接进来
            SocketChannel accept = serverSocketChannel.accept();
            long flag = 0;
            while (flag != -1) {
                flag  = accept.read(byteBuffer);
                byteBuffer.flip();
                channel.write(byteBuffer);
                byteBuffer.clear();
            }
        }
    }

 客户端

    public void client1() throws IOException {
        SocketChannel open = SocketChannel.open();
        open.connect(new InetSocketAddress("127.0.0.1", 9527));
        FileChannel channel = new FileInputStream("C:\\SwaggerToCL\\23.09.11-编程设码初始化介绍.mp4").getChannel();
        long l = System.currentTimeMillis();
        long length = channel.size();
        long begin = 0;
        long total = 0;
        long sum = 0;
        while (true) {
            //linux和window一次传输数据长度不一样,文件可能需要多次传输
            total = channel.transferTo(begin, length, open);
            sum += total;//记录传输总字节
            if (total < length) {//一次还没有传完
                //设置开始位置
                begin += total;
                //长度
                length -= total;
            } else {
                //传输完成
                break;
            }
        }
        long l1 = System.currentTimeMillis();
        System.out.println("传输文件所需时间:" + (l1 - l) + "传输总字节:" + sum);
        open.close();
        channel.close();
    }

 结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值