继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Netty使用

冰狐
关注TA
已关注
手记 20
粉丝 1
获赞 31

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中注册的方法执行.
打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP