java - 我怎样才能关闭netty客户端?

标签 java networking network-programming client netty

我想知道如何关闭 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();
  }
}

最佳答案

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

关于java - 我怎样才能关闭netty客户端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56612752/

相关文章:

javascript - 如何查询XMLHttpRequest的方法类型?

iphone - Objective-C : Retrieve Router address?

c - 为位于不同网络的节点定义 UDP 套接字

.net - 如何减少网络上运行的 .Net dll 数量

java - 如何向 JTextarea 添加文本而不删除它之前的文本? java

java - 如何从一个文件夹中单独获取 .png 文件

java - 将数组拆分为两个数组

python - 用于构建 TCP 服务器的良好 Python 网络库?

swift - GCDASyncScocket readDataToLength : with swift

JAVA:用时区解析日期