手记

Netty使用

java中使用NIO

  • 创建ServerSocketChannel
  • 把ServerSocketChannel注册到Selectot中
  • 调用select方法
  • 处理事件
accept:
	//接收客户端请求
	SocketChannel clientChannel = serverSocketChannel.accept();
	//注册客户端Channel到selector上, 监听其读写事件.
	clientChannel.register(select,SelectionKey.OP_READ);
read:
	//读取clientChannel中的数据到buff
	ByteBuffer buff = ByteBuffer.allocate(48);
	clientChannel.read(buff);
	//发送sendBuff中的数据到clientChannel中
	ByteBuffer sendBuff = ByteBuffer.allocate(12);
	sendBuff.put("123".getBytes());
	sendBuff.flip();
	clientChannel.write(sendBuff);

Netty封装NIO

  • 创建两个线程组, 一个用来处理accept请求, 一个用来处理read, write事件.
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
   NioEventLoopGroup workerGroup = new NioEventLoopGroup();
   ServerBootstrap bootstrap = new ServerBootstrap();
   bootstrap.group(bossGroup, workerGroup);
  • 设置接受accept事件的Channel, 与NIO中的ServerSocketChannel对应.
bootstrap.channel(NioServerSocketChannel.class);
  • 设置收到accept后返回的客户端Channel, 与NIO中的SocketChannel对应
bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
       ChannelPipeline channelPipeline = ch.pipeline();
       channelPipeline.addLast(new RpcDecoder());
    }
   });
  • 当客户端有read,write事件时, Netty使用ChannelInboundHandler, ChannelOutboundHandler来处理相应的事件, 我们重写这两个方法就可以自定义处理数据了.
  • 上述代码中的addLast就是把该clientChannel对应的read, write事件的处理方法注册到pipeline上.
  • workerGroup线程组会根据pipeline中注册的方法执行.
0人推荐
随时随地看视频
慕课网APP