我想知道如何关闭网络客户

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();
  }
}

最佳答案

您需要在客户端启动期间保留对客户端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;
}

10-04 21:28