channel的主要作用

  • close()可以用来关闭channel
  • closeFuture()用来处理channel的关闭
    • sync方法作用是同步等待channel关闭
    • 而addListener方法是异步等待channel关闭
  • pipeline()方法添加处理器
  • write()方法将数据写入
  • writeAndFlush()方法将数据写入并刷出

ChannelFuture

用于配合异步方法处理返回结果

  1. ChannelFuture future = new Bootstrap()
  2. .group(new NioEventLoopGroup())
  3. .channel(NioSocketChannel.class)
  4. .handler(new ChannelInitializer<NioSocketChannel>() {
  5. @Override
  6. protected void initChannel(NioSocketChannel sh) throws Exception {
  7. sh.pipeline().addLast(new StringEncoder());
  8. }
  9. })
  10. //异步非阻塞,main发起来调用,真正执行connect的nio线程
  11. .connect(new InetSocketAddress("localhost", 8080));
  12. //如果不在此进行同步阻塞,便会直接去获取channel,但此时还没有连接完成
  13. future.sync().channel().writeAndFlush("hello,world");

处理关闭连接后的操作

NioEventLoopGroup group = new NioEventLoopGroup();
ChannelFuture future = new Bootstrap()
    .group(group)
    .channel(NioSocketChannel.class)
    .handler(new ChannelInitializer<NioSocketChannel>() {
        @Override
        protected void initChannel(NioSocketChannel sh) throws Exception {
            sh.pipeline().addLast(new StringEncoder());
        }
    })
    //异步非阻塞,main发起来调用,真正执行connect的nio线程
    .connect(new InetSocketAddress("localhost", 8080));
//如果不在此进行同步阻塞,便会直接去获取channel,但此时还没有连接完成
Channel channel = future.sync().channel();
new Thread(()->{
    Scanner scanner = new Scanner(System.in);
    while (true){
        String line = scanner.nextLine();
        if("q".equals(line)){
            channel.close();
            break;
        }
        channel.writeAndFlush(line);
    }
}).start();

ChannelFuture channelFuture = channel.closeFuture();

channelFuture.addListener(new ChannelFutureListener() {
    @Override
    public void operationComplete(ChannelFuture channelFuture) throws Exception {
        System.out.println("处理关闭之后的操作");
        group.shutdownGracefully();
    }
});