在 channelFuture 上调用 sync 不会阻塞线程

calling sync on channelFuture is not blocking the thread

我有一个 netty 客户端连接到远程服务器以进行请求-响应循环。我想阻塞直到远程连接成功并且我已经解析了响应。

我就是这样做的

Channel ch = bootstrap.connect(addr).sync().channel();
            ChannelFuture f = ch.writeAndFlush(obj);
            f.sync();
            f.channel().close();
       System.out.println("hello world");

在我的处理程序上

MyHandler extends ChannelInboundHandlerAdapter {

     static Map<String,Object> = new HashMap<>();
       @Override
    public void channelRead(final ChannelHandlerContext ctx, Object msg) {
       System.out.println("foo bar");
        if (msg instanceof FullHttpResponse) {
            parseAndPutInMap(msg);
         }
        ctx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }
}

我观察到调用 f.sync() 没有阻塞。我看到 "hello world" 在 "foo bar" 之前立即打印出来。我还浏览了调试器,但在调用 f.sync() 后没有看到 channelRead 命中。

所以这里出了什么问题?我希望此操作被阻止,因为我需要在决定要做什么之前处理响应。

您的操作实际上是阻塞的,它会等到 "writing" 完成。

但这对你来说是个问题,因为你想等到 "reading" 完成。

您可以做的一件事是 "syncing" 在不久的将来关闭频道,然后在您完成阅读后在您的读取处理程序中关闭频道。

Channel ch = bootstrap.connect(addr).sync().channel();
ChannelFuture f = ch.writeAndFlush(obj);
f.sync(); // Also sync on this, so its error automatically get thrown
ch.closeFuture().sync();
System.out.println("hello world");
MyHandler extends ChannelInboundHandlerAdapter {

     static Map<String,Object> = new HashMap<>();
       @Override
    public void channelRead(final ChannelHandlerContext ctx, Object msg) {
       System.out.println("foo bar");
        if (msg instanceof FullHttpResponse) {
            parseAndPutInMap(msg);
         }
        // The following line automatically closes the channel:
        ctx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }
}