在channelFuture上调用sync不会阻止线程 [英] calling sync on channelFuture is not blocking the thread

查看:1829
本文介绍了在channelFuture上调用sync不会阻止线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Netty客户端,它连接到远程服务器以进行请求-响应周期.我想阻止直到远程连接成功并且我已经解析了响应.

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.

这就是我要做的

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被击中.

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.

推荐答案

您的操作实际上正在阻塞,它会等到写入"完成为止.

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

这篇关于在channelFuture上调用sync不会阻止线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆