关于这个问题的帖子很少。但是我要寻找的是完全不同的。
从服务器收到响应后,netty客户端将被服务器响应阻止,并继续执行任何业务逻辑。
netty中的大多数示例都没有显示客户如何以阻塞的方式接收响应并进行处理。
我扔了一个可变的obj,并要求处理程序设置响应对象。 这就是我现在拥有的东西,我觉得很黑
public class MutableObj {
FullHttpResponse response;
}
MutableObj mutable = new MutableObj();
Bootstrap bootstap = new Bootstrap()
.group(bossGroup())
.channel(NioSocketChannel.class)
.handler(MyChannelInitializer(mutable));
Channel ch = bootstrap.connect(addr).sync().channel();
ChannelFuture f = ch.writeAndFlush(obj);
f.sync();
ch.closeFuture().sync();
//since connection was blocked, I will have response object populated
FullHttpResonse response = mutable.getResponse();
//now process the response
MyHandler extends ChannelInboundHandlerAdapter {
MutableObj obj;
public MyHandler(MutableObj obj) {
this.obj=obj;
}
@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) {
System.out.println("foo bar");
if (msg instanceof FullHttpResponse) {
obj.setResponse((FullHttpResponse) msg);
}
// The following line automatically closes the channel:
ctx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}
}
public class MyChannelIntializer extends ChannelInitializer<SocketChannel> {
private MutableObj obj;
@Override
public void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline();
p.addLast(new LoggingHandler(LogLevel.INFO));
p.addLast(new HttpClientCodec());
p.addLast(new HttpObjectAggregator(1024 * 1024, true));
p.addLast(new MyHandler(obj));
}
}
我的上述解决方案听起来很骇人,也不安全。 正确的做法是什么?
我经历过的相关帖子
Handling response from server in Netty client