简体   繁体   English

重用通道进行HTTP请求

[英]Reuse Channel for HTTP requests

I want to reuse channel for multiple HTTP requests. 我想为多个HTTP请求重用通道。 I'm using java+netty for the server but clients could be written in C#/Java. 我在服务器上使用java + netty,但是客户端可以用C#/ Java编写。

For the C# client I'm using HttpWebRequest with KeepAlive = true; 对于C#客户端,我将HttpWebRequestKeepAlive = true;一起使用KeepAlive = true; and I don't close the channel after the arrival of the response. 而且在回应到达后我不会关闭频道。 And it works perfect. 而且效果很好。

But when I tried the same for java <--> java communication I had some problems. 但是,当我尝试对Java <-> Java通信进行相同操作时,我遇到了一些问题。 I'm handling the responses from server something like in this sample and this client part. 我正在处理来自服务器的响应,例如示例和客户端部分。

If in if (msg instanceof LastHttpContent) { section I just do ctx.close(); 如果在if (msg instanceof LastHttpContent) {部分中,我只是做ctx.close(); I won't be able to reuse this channel again. 我将无法再次使用此频道。 What should I do here to be able to reuse it? 我在这里应该怎么做才能重用它?

I tried: 我试过了:

ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));

or 要么

ctx.writeAndFlush(Unpooled.EMPTY_BUFFER);

or tried to do nothing...but when I try to reuse this channel, i have problem in this handle. 或尝试不执行任何操作...但是当我尝试重用此通道时,此句柄出现问题。 The first request was handled fine, but the second gives me this error: 第一个请求处理得很好,但是第二个给我这个错误:

channelRead0: DefaultHttpResponse(decodeResult: failure(java.lang.NullPointerException), version: HTTP/1.1)

Section if (msg instanceof HttpResponse) works fine (I mean headers was read), but throws exception somewhere after that. if (msg instanceof HttpResponse)工作正常(我的意思是读取了标头),但此后在某处引发了异常。

And: 和:

headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);

doesn't help too. 也无济于事。 To make it clear: 1st request/response is fine. 明确说明:第一个请求/响应很好。 Second request in same stream is fine, but there is a problem in decoding the response. 同一流中的第二个请求很好,但是在解码响应时存在问题。

I checked Logger. 我检查了记录仪。 1st and second responses are equal, so I don't understand why it gets NullException when decoding it. 第一个和第二个响应是相等的,所以我不明白为什么在解码它时会得到NullException。

ps netty 4.0.26 ps netty 4.0.26

You are entirely at the mercy of the clients. 您完全由客户摆布。 If they implement connection pooling, your connection will be reused. 如果他们实现连接池,则您的连接将被重用。 If not, not. 如果没有,那就没有。 Nothing you can do about it at the server end except observe and implement the Connection: close header if sent. 在服务器端,除了观察并实现Connection: close标头(如果已发送)之外,您无能为力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM