calling sync on channelFuture is not blocking the

2019-08-18 06:30发布

I have a netty client that connect to remote server for a request-response cycle. I want to block till the remote connection is successful and I have parsed the response.

Here is what I do

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

On my handler

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

what I observed is calling f.sync() is not blocking. I see "hello world" printed right away before "foo bar". I also navigated through the debugger and did not see channelRead hit right after f.sync() is called.

so what is wrong here? I want this operation to be blocking since I need to process response before I decide what to do.

标签: netty
1条回答
混吃等死
2楼-- · 2019-08-18 07:21

Your operation is actually blocking, it waits till "writing" has been finished.

But this is a problem for you, as you want to wait till "reading" has been finished.

One of the things you could do is "syncing" on the close future of the channel, and then close the channel in your read handler when you are done reading.

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);
    }
}
查看更多
登录 后发表回答