gpt4 book ai didi

java - Netty - 对同一连接的第二次请求

转载 作者:行者123 更新时间:2023-12-02 06:54:30 27 4
gpt4 key购买 nike

当我发送第二个请求时,处理程序不处理响应,代码如下:

public class Test extends SimpleChannelUpstreamHandler {
protected boolean close = false;

public static void main(String[] args) throws URISyntaxException {
String url = "http://example.com";
ChannelFactory channelFactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
final URI uri = new URI(url);
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("codec", new HttpClientCodec());
pipeline.addLast("inflater", new HttpContentDecompressor());
pipeline.addLast("aggregator", new HttpChunkAggregator(1048576));
pipeline.addLast("handler", new Test());
Channel channel = channelFactory.newChannel(pipeline);
InetSocketAddress inetAddress = new InetSocketAddress(uri.getHost(), 80);
channel.connect(inetAddress).addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) throws Exception {
System.out.println("connected");
Channel channel = future.getChannel();
if (!future.isSuccess()) {
future.getCause().printStackTrace();
} else {
HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString());
request.setHeader(HttpHeaders.Names.HOST, uri.getHost());
request.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
request.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
channel.write(request);
System.out.println("sent first request");
}

}
});
}



@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
System.out.println("done");
if (!close) {
URI uri = new URI("http://example.com");
HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString());
request.setHeader(HttpHeaders.Names.HOST, uri.getHost());
request.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
request.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
e.getChannel().write(request).addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture arg0) throws Exception {
System.out.println("sent second request");
}
});
close = true;
} else {
ctx.getChannel().close();
System.out.println("closing");
}
}


}

在输出中我只看到:

connected
sent first request
done
sent second request

为什么没有第二个“完成”?

最佳答案

您指示服务器关闭连接,因此这可能就是正在发生的情况(添加一个channelClosed()方法来检查)。这实际上是幸运的,否则您将创建一个无限循环(直到 example.com 的运算符(operator)将您作为 DOS 攻击列入黑名单;-))。

关于java - Netty - 对同一连接的第二次请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17564809/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com