Netty-不关闭通道的TCP客户端接收响应

时间:2019-06-03 02:35:12

标签: tcp netty

我想创建不关闭通道即可接收响应的TCP客户端。我正在使用Netty并在此处引用回显示例“ https://netty.io/4.1/xref/io/netty/example/echo/EchoClient.html”。

似乎每个Netty示例TCP客户端都有以下代码。

f.channel().closeFuture().sync();

这一直等到通道关闭。由于我试图创建类似TCP连接的保持活动状态,因此我不希望TCP客户端和服务器都关闭通道。

如果我不使用上面的代码,则TCP客户端无需等待响应即可完成该过程。我希望TCP客户端等待直到它收到响应,但是我不想使用ReadTimeoutHandler,因为即使TCP客户端已经完成接收响应,它也一直等待。

是否有一种方法可以等到“ channelReadComplete()”被调用?

f.channel().closeFuture().sync();

我想更改上面的代码以等待调用“ channelReadComplete()”。

EventLoopGroup group = new NioEventLoopGroup();
try {
    Bootstrap b = new Bootstrap();
    b.group(group)
     .channel(NioSocketChannel.class)
     .option(ChannelOption.TCP_NODELAY, true)
     .handler(new ChannelInitializer<SocketChannel>() {
         @Override
         public void initChannel(SocketChannel ch) throws Exception {
             ChannelPipeline p = ch.pipeline();
             if (sslCtx != null) {
                 p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
             }
             //p.addLast(new LoggingHandler(LogLevel.INFO));
             p.addLast(new EchoClientHandler());
         }
     });

    // Start the client.
    System.out.println("CLIENT - connect");
    ChannelFuture f = b.connect(HOST, PORT).sync();

    // Wait until the connection is closed.
    System.out.println("CLIENT - closeFuture");
    f.channel().closeFuture().sync();

0 个答案:

没有答案
相关问题