Netty框架入门-Service与Client的NIO通信示例

知识点:

  1. Netty框架如何引导服务端监听网络端口并读写消息
  2. Netty框架如何连接远程服务器并读写消息
  3. Netty框架ChannelInboundHandlerAdapter部分事件使用方法
  4. Netty框架Channel管道使用方法

前言

上一篇对Netty框架做了一个大概的介绍,并对核心部件Channel、ChannelHeadler、Future、事件从概念与作用上做了说明,另外还与Java NIO 在编码上做了一个简单的对比,引出了EventLoop。本篇使用一个小示例来了解下Netty框架怎么使用,真正的用起来。

交互图

image-20210707054544322

服务端示例

public static void main(String[] args) throws InterruptedException {
   
  //创建EventLoop
  NioEventLoopGroup master = new NioEventLoopGroup();
  //创建服务端引导
  ServerBootstrap bootstrap = new ServerBootstrap();
  bootstrap.group(master);
  bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
  //指定使用NioServerSocketChannel作为Channel类型
  bootstrap.channel(NioServerSocketChannel.class);
  //注册一个ChannelInboundHandlerAdapter类型处理channel的连接
  bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
   
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
   
      //在channel的pipeline中加入消息处理类型为ChannelInboundHandlerAdapter
      ch.pipeline().addLast(new MessageChannel());
    }
  });
  //使用bind方法启动服务端的监听
  ChannelFuture future = bootstrap.bind(30888).sync();
  future.channel().closeFuture().sync();
  master.shutdownGracefully().sync(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值