Netty学习笔记十三、NIO与零拷贝代码理解

一、概念

1、零拷贝从操作系统角度看,是没有cpu拷贝,既CPU拷贝数据很少可以忽略。

二、代码

package com.hao.demo.netty;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

/**
 * @author haoxiansheng
 * @date 2020-05-19
 */
public class NewIOClient {

    public static void main(String[] args) throws IOException {

        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("loacllhost", 7001));

        String fileName = "hao.zip";

        // 得到一个FileChannel
        FileChannel fileChannel = new FileInputStream(fileName).getChannel();

        // 准备发送
        long startTime = System.currentTimeMillis();

        // 在linux 下一个transferTo 方法就可以完成传输
        // 在windoes 下一次调用transferTo 只能发送8m,就需要分段传输文件,而且要注意传输的额位置  自己计算
        // 做个算发transferTo(position, fileChannel.size(), socketChannel)

        // transferTo 底层使用倒零拷贝 可以区里面看一下他方法的描述
        long transferCount = fileChannel.transferTo(0, fileChannel.size(), socketChannel);

        System.out.println("发送总的字节数 = " + transferCount + "耗时" + (System.currentTimeMillis() - startTime));

        // 关闭
        fileChannel.close();

    }
}


package com.hao.demo.netty;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author haoxiansheng
 * @date 2020-05-19
 */
// 服务器端
public class NewIOServer {

    public static void main(String[] args) throws IOException {

        InetSocketAddress address = new InetSocketAddress(7001);

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        ServerSocket serverSocket = serverSocketChannel.socket();

        serverSocket.bind(address);

        // 创建buffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        while (true) {
            SocketChannel socketChannel = serverSocketChannel.accept(); // 监听

            int readCount = 0;
            while (readCount != -1) {
                try{
                    readCount = socketChannel.read(byteBuffer);
                } catch (Exception e) {
                  break;
                }
                //
                byteBuffer.rewind(); // 倒袋 position = 0 mark 作废

            }
        }

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值