简体   繁体   中英

How could I shutdown a netty client?

I wonder how I could shut down a netty client

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

You need to hold the reference to the client Channel and EventLoopGroup during the start of the client and close it when necessary.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM