Netty 在channelFuture上调用同步不会阻塞线程

Netty 在channelFuture上调用同步不会阻塞线程,netty,Netty,我有一个netty客户机,它连接到远程服务器,进行请求-响应循环。我想阻止,直到远程连接成功并解析了响应 我就是这么做的 Channel ch = bootstrap.connect(addr).sync().channel(); ChannelFuture f = ch.writeAndFlush(obj); f.sync(); f.channel().close(); System.out.println(

我有一个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);
    }
}
MyHandler扩展ChannelInboundHandlerAdapter{
静态映射=新的HashMap();
@凌驾
公共无效channelRead(最终ChannelHandlerContext ctx,对象消息){
System.out.println(“foo-bar”);
if(msg instanceof FullHttpResponse){
parseAndPutInMap(msg);
}
ctx.channel();
}
}
我观察到调用f.sync()没有阻塞。我看到“foo bar”前面马上印着“hello world”。我还浏览了调试器,在调用f.sync()之后没有看到channelRead命中


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

您的操作实际上正在阻塞,它将等待“写入”完成

但这对你来说是个问题,因为你想等到“阅读”完成

您可以做的一件事是“同步”通道的未来,然后在您完成读取后关闭读取处理程序中的通道

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扩展ChannelInboundHandlerAdapter{
静态映射=新的HashMap();
@凌驾
公共无效channelRead(最终ChannelHandlerContext ctx,对象消息){
System.out.println(“foo-bar”);
if(msg instanceof FullHttpResponse){
parseAndPutInMap(msg);
}
//以下行自动关闭通道:
ctx.channel();
}
}

当我尝试在closeFuture上添加同步时,我注意到打印语句是按顺序出现的,但我在handler#ChannelRead中有一个调试器,它从未被命中。为什么会这样?我在ch.closeFuture.sync()之后添加了f.channel().close()。这是否不必要?对此有何想法?不需要调用close,因为您已经在chanelRead方法中关闭了频道。但建议在同步方法引发异常的情况下关闭通道为什么调试器从未被命中?如果调用close,则在接收到任何内容之前关闭通道,并且由于未接收任何内容,因此调试器从未被命中
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);
    }
}