Netty4.0学习笔记系列之三:构建简单的http服务(转)
http://blog.csdn.net/u013252773/article/details/21254257
本文主要介绍如何通过Netty构建一个简单的http服务。
想要实现的目的是:
1、Client向Server发送http请求。
2、Server端对http请求进行解析。
3、Server端向client发送http响应。
4、Client对http响应进行解析。
在该实例中,会涉及到http请求的编码、解码,http响应的编码、解码,幸运的是,Netty已经为我们提供了这些工具,整个实例的逻辑图如下所示:
其中红色框中的4个类是Netty提供的,它们其实也是一种Handler,其中Encoder继承自ChannelOutboundHandler,Decoder继承自ChannelInboundHandler,它们的作用是:
1、HttpRequestEncoder:对httpRequest进行编码。
2、HttpRequestDecoder:把流数据解析为httpRequest。
3、HttpResponsetEncoder:对httpResponset进行编码。
4、HttpResponseEncoder:把流数据解析为httpResponse。
该实例涉及到的类有5个:HttpServer HttpServerInboundHandler HttpClient HttpClientInboundHandler ByteBufToBytes
1、HttpServer 启动http服务器
- package com.guowl.testhttpprotocol;
- import io.netty.bootstrap.ServerBootstrap;
- import io.netty.channel.ChannelFuture;
- import io.netty.channel.ChannelInitializer;
- import io.netty.channel.ChannelOption;
- import io.netty.channel.EventLoopGroup;
- import io.netty.channel.nio.NioEventLoopGroup;
- import io.netty.channel.socket.SocketChannel;
- import io.netty.channel.socket.nio.NioServerSocketChannel;
- import io.netty.handler.codec.http.HttpRequestDecoder;
- import io.netty.handler.codec.http.HttpResponseEncoder;
- public class HttpServer {
- public void start(int port) throws Exception {
- EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
- EventLoopGroup workerGroup = new NioEventLoopGroup();
- try {
- ServerBootstrap b = new ServerBootstrap(); // (2)
- b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) // (3)
- .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
- @Override
- public void initChannel(SocketChannel ch) throws Exception {
- // server端发送的是httpResponse,所以要使用HttpResponseEncoder进行编码
- ch.pipeline().addLast(new HttpResponseEncoder());
- // server端接收到的是httpRequest,所以要使用HttpRequestDecoder进行解码
- ch.pipeline().addLast(new HttpRequestDecoder());
- ch.pipeline().addLast(new HttpServerInboundHandler());
- }
- }).option(ChannelOption.SO_BACKLOG, 128) // (5)
- .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)
- ChannelFuture f = b.bind(port).sync(); // (7)
- f.channel().closeFuture().sync();
- } finally {
- workerGroup.shutdownGracefully();
- bossGroup.shutdownGracefully();
- }
- }
- public static void main(String[] args) throws Exception {
- HttpServer server = new HttpServer();
- server.start(8000);
- }
- }
2、HttpServerInboundHandler 解析客户端的请求,并进行响应
- package com.guowl.testhttpprotocol;
- import static io.netty.handler.codec.http.HttpHeaders.Names.CONNECTION;
- import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
- import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
- import static io.netty.handler.codec.http.HttpResponseStatus.OK;
- import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
- import io.netty.buffer.ByteBuf;
- import io.netty.buffer.Unpooled;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.ChannelInboundHandlerAdapter;
- import io.netty.handler.codec.http.DefaultFullHttpResponse;
- import io.netty.handler.codec.http.FullHttpResponse;
- import io.netty.handler.codec.http.HttpContent;
- import io.netty.handler.codec.http.HttpHeaders;
- import io.netty.handler.codec.http.HttpHeaders.Values;
- import io.netty.handler.codec.http.HttpRequest;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import com.guowl.utils.ByteBufToBytes;
- public class HttpServerInboundHandler extends ChannelInboundHandlerAdapter {
- private static Logger logger = LoggerFactory.getLogger(HttpServerInboundHandler.class);
- private ByteBufToBytes reader;
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- if (msg instanceof HttpRequest) {
- HttpRequest request = (HttpRequest) msg;
- System.out.println("messageType:" + request.headers().get("messageType"));
- System.out.println("businessType:" + request.headers().get("businessType"));
- if (HttpHeaders.isContentLengthSet(request)) {
- reader = new ByteBufToBytes((int) HttpHeaders.getContentLength(request));
- }
- }
- if (msg instanceof HttpContent) {
- HttpContent httpContent = (HttpContent) msg;
- ByteBuf content = httpContent.content();
- reader.reading(content);
- content.release();
- if (reader.isEnd()) {
- String resultStr = new String(reader.readFull());
- System.out.println("Client said:" + resultStr);
- FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer("I am ok"
- .getBytes()));
- response.headers().set(CONTENT_TYPE, "text/plain");
- response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
- response.headers().set(CONNECTION, Values.KEEP_ALIVE);
- ctx.write(response);
- ctx.flush();
- }
- }
- }
- @Override
- public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
- logger.info("HttpServerInboundHandler.channelReadComplete");
- ctx.flush();
- }
- }
3、HttpClient 向服务器发送请求
- package com.guowl.testhttpprotocol;
- import io.netty.bootstrap.Bootstrap;
- import io.netty.buffer.Unpooled;
- import io.netty.channel.ChannelFuture;
- import io.netty.channel.ChannelInitializer;
- import io.netty.channel.ChannelOption;
- import io.netty.channel.EventLoopGroup;
- import io.netty.channel.nio.NioEventLoopGroup;
- import io.netty.channel.socket.SocketChannel;
- import io.netty.channel.socket.nio.NioSocketChannel;
- import io.netty.handler.codec.http.DefaultFullHttpRequest;
- import io.netty.handler.codec.http.HttpHeaders;
- import io.netty.handler.codec.http.HttpMethod;
- import io.netty.handler.codec.http.HttpRequestEncoder;
- import io.netty.handler.codec.http.HttpResponseDecoder;
- import io.netty.handler.codec.http.HttpVersion;
- import java.net.URI;
- public class HttpClient {
- public void connect(String host, int port) throws Exception {
- EventLoopGroup workerGroup = new NioEventLoopGroup();
- try {
- Bootstrap b = new Bootstrap(); // (1)
- b.group(workerGroup); // (2)
- b.channel(NioSocketChannel.class); // (3)
- b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
- b.handler(new ChannelInitializer<SocketChannel>() {
- @Override
- public void initChannel(SocketChannel ch) throws Exception {
- // 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码
- ch.pipeline().addLast(new HttpResponseDecoder());
- // 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码
- ch.pipeline().addLast(new HttpRequestEncoder());
- ch.pipeline().addLast(new HttpClientInboundHandler());
- }
- });
- // Start the client.
- ChannelFuture f = b.connect(host, port).sync(); // (5)
- URI uri = new URI("http://127.0.0.1:8000");
- String msg = "Are you ok?";
- DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
- uri.toASCIIString(), Unpooled.wrappedBuffer(msg.getBytes()));
- // 构建http请求
- request.headers().set(HttpHeaders.Names.HOST, host);
- request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
- request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());
- request.headers().set("messageType", "normal");
- request.headers().set("businessType", "testServerState");
- // 发送http请求
- f.channel().write(request);
- f.channel().flush();
- f.channel().closeFuture().sync();
- } finally {
- workerGroup.shutdownGracefully();
- }
- }
- public static void main(String[] args) throws Exception {
- HttpClient client = new HttpClient();
- client.connect("127.0.0.1", 8000);
- }
- }
4、HttpClientInboundHandler 对服务器的响应进行读取
- package com.guowl.testhttpprotocol;
- import io.netty.buffer.ByteBuf;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.ChannelInboundHandlerAdapter;
- import io.netty.handler.codec.http.HttpContent;
- import io.netty.handler.codec.http.HttpHeaders;
- import io.netty.handler.codec.http.HttpResponse;
- import com.guowl.utils.ByteBufToBytes;
- public class HttpClientInboundHandler extends ChannelInboundHandlerAdapter {
- private ByteBufToBytes reader;
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- if (msg instanceof HttpResponse) {
- HttpResponse response = (HttpResponse) msg;
- System.out.println("CONTENT_TYPE:" + response.headers().get(HttpHeaders.Names.CONTENT_TYPE));
- if (HttpHeaders.isContentLengthSet(response)) {
- reader = new ByteBufToBytes((int) HttpHeaders.getContentLength(response));
- }
- }
- if (msg instanceof HttpContent) {
- HttpContent httpContent = (HttpContent) msg;
- ByteBuf content = httpContent.content();
- reader.reading(content);
- content.release();
- if (reader.isEnd()) {
- String resultStr = new String(reader.readFull());
- System.out.println("Server said:" + resultStr);
- ctx.close();
- }
- }
- }
- }
5、ByteBufToBytes 读取NIO的工具类,可以一次性把ByteBuf的数据读取出来,也可以把多次ByteBuf中的数据统一读取出来。
- package com.guowl.utils;
- import io.netty.buffer.ByteBuf;
- import io.netty.buffer.Unpooled;
- public class ByteBufToBytes {
- private ByteBuf temp;
- private boolean end = true;
- public ByteBufToBytes(int length) {
- temp = Unpooled.buffer(length);
- }
- public void reading(ByteBuf datas) {
- datas.readBytes(temp, datas.readableBytes());
- if (this.temp.writableBytes() != 0) {
- end = false;
- } else {
- end = true;
- }
- }
- public boolean isEnd() {
- return end;
- }
- public byte[] readFull() {
- if (end) {
- byte[] contentByte = new byte[this.temp.readableBytes()];
- this.temp.readBytes(contentByte);
- this.temp.release();
- return contentByte;
- } else {
- return null;
- }
- }
- public byte[] read(ByteBuf datas) {
- byte[] bytes = new byte[datas.readableBytes()];
- datas.readBytes(bytes);
- return bytes;
- }
- }
注意事项:
1、可以通过在Netty的Chanel中发送HttpRequest对象,完成发送http请求的要求,同时可以对HttpHeader进行设置。
2、可以通过HttpResponse发送http响应,同时可以对HttpHeader进行设置。
3、上面涉及到的http对象都是Netty自己封装的,不是标准的。
Netty4.0学习笔记系列之三:构建简单的http服务(转)的更多相关文章
- Netty4.0学习笔记系列之一:Server与Client的通讯
http://blog.csdn.net/u013252773/article/details/21046697 本文是学习Netty的第一篇文章,主要对Netty的Server和Client间的通讯 ...
- Netty4.0学习笔记系列之二:Handler的执行顺序(转)
http://blog.csdn.net/u013252773/article/details/21195593 Handler在netty中,无疑占据着非常重要的地位.Handler与Servlet ...
- Netty4.0学习笔记系列之四:混合使用coder和handler
Handler如何使用在前面的例子中已经有了示范,那么同样是扩展自ChannelHandler的Encoder和Decoder,与Handler混合后又是如何使用的?本文将通过一个实际的小例子来展示它 ...
- Netty4.0学习笔记系列之二:Handler的执行顺序
Handler在netty中,无疑占据着非常重要的地位.Handler与Servlet中的filter很像,通过Handler可以完成通讯报文的解码编码.拦截指定的报文.统一对日志错误进行处理.统一对 ...
- WebService学习笔记系列(二)
soap(简单对象访问协议),它是在http基础之上传递xml格式数据的协议.soap协议分为两个版本,soap1.1和soap1.2. 在学习webservice时我们有一个必备工具叫做tcpmon ...
- .NET CORE学习笔记系列(2)——依赖注入【1】控制反转IOC
原文:https://www.cnblogs.com/artech/p/net-core-di-01.html 一.流程控制的反转 IoC的全名Inverse of Control,翻译成中文就是“控 ...
- DirectX 总结和DirectX 9.0 学习笔记
转自:http://www.cnblogs.com/graphics/archive/2009/11/25/1583682.html DirectX 总结 DDS DirectXDraw Surfac ...
- 步步为营 SharePoint 开发学习笔记系列总结
转:http://www.cnblogs.com/springyangwc/archive/2011/08/03/2126763.html 概要 为时20多天的sharepoint开发学习笔记系列终于 ...
- .NET CORE学习笔记系列(2)——依赖注入[6]: .NET Core DI框架[编程体验]
原文https://www.cnblogs.com/artech/p/net-core-di-06.html 毫不夸张地说,整个ASP.NET Core框架是建立在一个依赖注入框架之上的,它在应用启动 ...
随机推荐
- 【译】Android应用架构
Android开发生态圈的节奏非常之快.每周都会有新的工具诞生,类库的更新,博客的发表以及技术探讨.如果你外出度假一个月,当你回来的时候可能已经发布了新版本的Support Library或者Play ...
- iOS UI控件继承关系图
闲来无事,把UI控件的继承关系图整理下来,供自己和大家使用.
- php 多维数组转换
把字符类型转换成时间类型的,先用foreach遍历出来时间,在通过时间函数转换成时间格式; 例子: <?phpecho "<pre>";$lsrfield = a ...
- 2.添加键盘钩子。向进程中注入dll
学习笔记 1.首先要建立mfc的动态链接库.在def文件中放入要导出的函数名. 2.添加函数如下 //安装钩子 //HHOOK SetWindowsHookEx( // int idHook,//钩子 ...
- MVC+MEF+UnitOfWork+EF架构,网站速度慢的原因总结!(附加ANTS Memory Profiler简单用法)
(最近使用内存分析工具ANTS Memory Profiler,以及其他网友提供的意见发现最终导致内存泄漏的就是MEF,在此特地更新下,与大家分享!最下面红色字体) 最近参考使用了郭明峰的一套架构来做 ...
- 在ASP中调用DLL的方法
.net的dll已经不是严格意义上的动态连接库了,而是一个类或者类库.它是不能直接在ASP.VB等其它的应用环境中使用的. 我们可以通过COM包装器(COM callable wrapper (C ...
- PHP代码批量加密
<?php error_reporting(E_ALL); ini_set('display_errors','1'); //批量加密码当前目录 $dirnow = getcwd(); $dir ...
- IE6解决固定定位代码
有些朋友在进行网页布局时,会遇到IE6浏览器不支持固定定位的兼容性问题,本博将详细介绍此问题的解决方法,需要了解的朋友可以参考下. ie6 垂直居中固定定位,代码如下: #center {_posit ...
- 【POJ3468】【树状数组区间修改】A Simple Problem with Integers
Description You have N integers, A1, A2, ... , AN. You need to deal with two kinds of operations. On ...
- 读书笔记之 - javascript 设计模式 - 单体模式
单体是一个用来划分命名空间,并将一批相关方法和属性组织在一起的对象,如果它可以被实例化,那么它只能被实例化一次. 单体模式,就是将代码组织为一个逻辑单元,这个逻辑单元中的代码可以通过单一的变量进行访问 ...