Practical Netty (6) HTTP Server/Client

news/2024/7/3 3:38:54

Practical Netty (6) HTTP Server/Client

  • 作者:柳大·Poechant(钟超)
  • 邮箱:zhongchao.ustc#gmail.com(# -> @)
  • 博客:Blog.CSDN.net/Poechant
  • 微博:weibo.com/lauginhom
  • 日期:June 18th, 2012

Netty 提供的 HTTP 功能,比较适合在 Netty 搭建的 TCP 或 UDP 服务器上做一些专用的 HTTP 服务,而非一般性的通用 HTTP 服务器。所以不要将 Netty 的自行实现的 HTTP 服务器的易用性与现有 Nginx、Lighttpd 等来比较。

1 HTTP Server

主要不同就是 Pipeline 用什么 handlers,以及我们自定义的 handler 如何处理 HttpRequest,并生成相应的 HttpResponse。

public class ServerPipelineFactory implements ChannelPipelineFactory {

    public ChannelPipeline getPipeline() throws Exception {
        ChannelPipeline pipeline = Channels.pipeline();

        pipeline.addLast("decoder", new HttpRequestDecoder());
        pipeline.addLast("aggregator", new HttpChunkAggregator(1048576));
        pipeline.addLast("encoder", new HttpResponseEncoder());
        pipeline.addLast("handler", new PoechantRequestHandler());

        return pipeline;
    }
}

如何接收 request?如何解析 request?如何产生 response?就看下面的 request handler。

public class PoechantRequestHandler extends SimpleChannelUpstreamHandler {
    @Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
            throws Exception {
        System.out.println("channel connected...");
        super.channelConnected(ctx, e);
    }
    
    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        HttpRequest request = (HttpRequest) e.getMessage();
        System.out.println(
            "request length:  " + 
            ((HttpRequest) e.getMessage()).getContent().readableBytes());
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
        response.setContent(ChannelBuffers.copiedBuffer("I'm a response", CharsetUtil.UTF_8));
        response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
        e.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
    }
}

在 Response 中 还可以设置其他的 Headers:

response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, 123);
response.setHeader("Content", "keep-alive");

还有一些 Headers 相关的 Name 和 Value,可以在HttpHeaders.NamesHttpHeaders.Values中找到。

2. HTTP Client

ClientBootstrap 一旦连接成功,就可以发送 HttpRequest 了,连接的代码实例如下:

Channel channel =
    cb.connect(
        new InetSocketAddress("10.0.0.110", 9980)).awaitUninterruptibly().getChannel();

如上是一个阻塞式的连接方式,在连接确认成功或失败前,会一直 block 在那里。异步的方式则如下:

ChannelFuture future = cb.connect(new InetSocketAddress("10.0.0.110", 9980));
Channel channel = future.getChannel();

然后就可以用这个 channel 发消息了。如果是异步的,则要监听成功之后再发送。

future.addListener(new ChannelFutureListener() {
    public void operationComplete(ChannelFuture future) throws Exception {
        // send a request to the http server
    }
});

然后就可以发送数据了。如果是异步的,

HttpRequest request = 
    new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/docs/index.html");
request.addHeader(HttpHeaders.Names.HOST, "10.0.0.110");
channel.write(request).awaitUninterruptibly().getChannel().getCloseFuture().awaitUninterruptibly();

当然你也可以异步发送。

channel.write(request);channel.write(request);

-

转载请注明来自柳大的CSDN博客:Blog.CSDN.net/Poechant,微博:weibo.com/lauginhom


http://www.niftyadmin.cn/n/3959855.html

相关文章

51 NOD 1406 and query

我们知道一个数S会对所有它的子集S产生1的贡献,但是我们直接枚举子集是 3^(log2 1000000)的,会炸掉;如果直接把每个有1的位变成0往下推也会凉掉,因为这样会有很多重复的。 但是我们发现 第二种方法其实算的是 有序的路径方案数&am…

java对象的内存计算

我们讨论的是java heap中对象所占内存。 1.基本类型内存占用 类型占用字节数boolean1byte1char2short2int4float4long8double82.对象所占内存由以下部分组成 object header, 8 byte基本类型,见第1节的表格引用类型,都为4 bytepadding&#…

[JavaScript]多文件上传时动态添加及删除文件选择框

多文件上传时,首先要解决的一个问题就是动态去添加或删除文件选择框,原来以为没多么困难的,但是没想到IE居然不支持table.appendChild()的js代码,导致整个前台JS的实现时间比原计划大大增加。不过还好可以借助网络查找需要的资源&…

第四周疑难点

18-20题的编程和解读不清楚? https://blog.csdn.net/a1015553840/article/details/50979640 c编译器有点问题,搞好IDE再回来。 林老师的优秀博客资料: https://blog.csdn.net/red_stone1/article/category/6956972转载于:https://www.cnblogs…

Netty初步 --概念

1.入门文档 如果是入门的话,官网的文档已经相当好了。里面的例子程序得仔细阅读,这里就不再重复转载了。参见http://netty.io/wiki/user-guide.html 2.为什么需要netty 2.1 主要是scalibity和performance 2.2 另外Netty In Action有一些说明,…

Ubuntu腾讯云主机安装分布式memcache服务器,C#中连接云主机进行存储的示例

Ubuntu腾讯云主机安装分布式memcache服务器,C#中连接云主机进行存储的示例(github代码:https://github.com/qq719862911/MemcacheTestDemo) 1、腾讯云安装memcache服务器,并且启动服务器。 1)安装Memcache服务端 sudo …

Practical Netty (3) 在Netty中使用Protobuf

Practical Netty (3) 在Netty中使用Protobuf 作者:柳大Poechant(钟超)邮箱:zhongchao.ustc#gmail.com(# -> )博客:Blog.CSDN.net/Poechant 微博:weibo.com/lauginhom 日期&#x…

Atom改国内源

linux #进入目录 cd /home/你的用户名/.atom#创建文件并编辑 vim .apmrc#添加国内源 registryhttps://registry.npm.taobao.org#保存退出#测试是否成功 apm install --check windows #进入目录 找到C:\Users\用户名\.atom目录#创建名为 .apmrc 的文件并编辑#添加国内源 registr…