如何使用Netty处理Http

如何使用Netty处理Http

本文介绍了如何使用Netty处理Http Keep-Alive连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个使用HTTP保持活动连接的HTTP客户端.当我从ClientBoostrap连接时,我得到了频道.我可以重用它发送多个HTTP请求吗?是否有任何示例演示HTTP Keep Alive功能?

I'm trying to write a HTTP client that uses HTTP keep-alive connections. When I connection from the ClientBoostrap I get the channel. Can I reuse this for sending multiple HTTP requests? Is there any examples demonstrating the HTTP Keep Alive functionality?

我还有另一个问题.现在,我的客户无需保持连接就可以工作.我在ClientHandler的messageReceived方法中调用channel.close.但是似乎连接没有关闭,一段时间后套接字用完了,我得到了BindException.任何指针将不胜感激.

Also I have another question. Now my client works without keep-alive connections. I'm calling the channel.close in the messageReceived method of the ClientHandler. But it seems the connections are not getting closed and after some time the sockets run out and I get a BindException. Any pointers will be really appreciated.

谢谢

推荐答案

只要通过类似于以下代码的代码行将Connection标头未设置为CLOSE(并且HttpVersion可能为1.1,尽管不确定),就可以了...

As long as the Connection header is not set to CLOSE (and possible the HttpVersion is 1.1, though uncertain) by a line of code similar to this...

request.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);

...您的频道应保持打开状态以用于多个请求/响应对.

...your channel should remain open for multiple request/response pairs.

这是我今天整理的一些示例代码以对其进行测试.您可以在关闭频道之前从Google退回任意数量的请求:

Here is some example code that I whipped up today to test it. You can bounce any number of requests off of Google prior to the channel closing:

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

这篇关于如何使用Netty处理Http Keep-Alive连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 20:56