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

时间:2019-05-22 23:11:07

标签: netty

我有一个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被命中。

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

1 个答案:

答案 0 :(得分:1)

您的操作实际上处于阻塞状态,它一直等到“写入”完成。

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

您可以做的一件事是在不久的将来与频道“同步”,然后在完成阅读后关闭阅读处理程序中的频道。

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);
    }
}