0

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();
  }
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621

1 Answers1

1

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;
}
Dmitriy Dumanskiy
  • 11,657
  • 9
  • 37
  • 57