【问题标题】:How could I shutdown a netty client?我怎么能关闭一个netty客户端?
【发布时间】:2019-10-29 22:50:43
【问题描述】:

我想知道如何关闭 netty 客户端

public void disconnect() {
  try {
    bootstrap.bind().channel().disconnect();
    dataGroup.shutdownGracefully();
    System.out.println(Strings.INFO_PREF + "Disconnected from server and stopped Client.");
  } catch (Exception ex) {
    ex.printStackTrace();
  }
}

【问题讨论】:

    标签: java networking network-programming client netty


    【解决方案1】:

    您需要在客户端启动期间保持对客户端ChannelEventLoopGroup的引用,并在必要时将其关闭。

    public void start() {
        NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup(1);
        Bootstrap b = new Bootstrap();
        b.group(nioEventLoopGroup)
         .channel(NioSocketChannel.class)
         .handler(getChannelInitializer());
    
        this.nioEventLoopGroup = nioEventLoopGroup;
        this.channel = b.connect(host, port).sync().channel();
    }
    
    //this method will return execution when client is stopped
    public ChannelFuture stop() {
        ChannelFuture channelFuture = channel.close().awaitUninterruptibly();
        //you have to close eventLoopGroup as well
        nioEventLoopGroup.shutdownGracefully();
        return channelFuture;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-09-20
      • 2016-04-04
      • 1970-01-01
      • 2018-07-17
      • 2019-09-11
      • 2014-10-07
      • 2015-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多