Java 如何使用Netty处理Http保持活动连接
我正在尝试编写一个使用HTTP保持活动连接的HTTP客户端。当我从ClientBoostrap连接时,我得到了频道。我可以重复使用它来发送多个HTTP请求吗?是否有任何示例演示HTTP保持活动功能 我还有一个问题。现在我的客户在没有保持活动连接的情况下工作。我正在调用Java 如何使用Netty处理Http保持活动连接,java,netty,Java,Netty,我正在尝试编写一个使用HTTP保持活动连接的HTTP客户端。当我从ClientBoostrap连接时,我得到了频道。我可以重复使用它来发送多个HTTP请求吗?是否有任何示例演示HTTP保持活动功能 我还有一个问题。现在我的客户在没有保持活动连接的情况下工作。我正在调用ClientHandler的messageReceived方法中的channel.close。但是连接似乎没有关闭,过了一段时间,套接字用完了,我得到了一个BindException。任何指点都将非常感激 谢谢,只要连接头没有通过类
ClientHandler
的messageReceived方法中的channel.close。但是连接似乎没有关闭,过了一段时间,套接字用完了,我得到了一个BindException
。任何指点都将非常感激
谢谢,只要连接头没有通过类似于以下的代码行设置为关闭(HttpVersion可能是1.1,尽管不确定),那么
request.setHeader(HttpHeaders.Names.CONNECTION,HttpHeaders.Values.CLOSE)代码>
…对于多个请求/响应对,您的通道应保持打开状态
下面是我今天编写的一些示例代码来测试它。在频道关闭之前,您可以从Google跳出任意数量的请求:
public class TestHttpClient {
static class HttpResponseReader extends SimpleChannelUpstreamHandler {
int remainingRequests = 2;
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
HttpResponse response = (HttpResponse) e.getMessage();
System.out.println("Beginning -------------------");
System.out.println(new String(response.getContent().slice(0, 50).array()));
System.out.println("End -------------------\n");
if(remainingRequests-- > 0)
sendRequest(ctx.getChannel());
else
ctx.getChannel().close();
}
}
public static void main(String[] args) {
ClientBootstrap bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory());
bootstrap.setPipeline(Channels.pipeline(
new HttpClientCodec(),
new HttpResponseReader()));
// bootstrap.setOption("child.keepAlive", true); // no apparent effect
ChannelFuture future = bootstrap.connect(new InetSocketAddress("google.com", 80));
Channel channel = future.awaitUninterruptibly().getChannel();
channel.getCloseFuture().addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) throws Exception {
// this winds up getting called immediately after the receipt of the first message by HttpResponseReader!
System.out.println("Channel closed");
}
});
sendRequest(channel);
while(true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static void sendRequest(Channel channel) {
// Prepare the HTTP request.
HttpRequest request = new DefaultHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.GET, "http://www.google.com");
request.setHeader(HttpHeaders.Names.HOST, "google.com");
request.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
channel.write(request);
}
}
sleep()
不可能是处理此问题的理想方法。它也与答案无关,但只是在示例中阻止主线程