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服务器

  1. package com.guowl.testhttpprotocol;
  2. import io.netty.bootstrap.ServerBootstrap;
  3. import io.netty.channel.ChannelFuture;
  4. import io.netty.channel.ChannelInitializer;
  5. import io.netty.channel.ChannelOption;
  6. import io.netty.channel.EventLoopGroup;
  7. import io.netty.channel.nio.NioEventLoopGroup;
  8. import io.netty.channel.socket.SocketChannel;
  9. import io.netty.channel.socket.nio.NioServerSocketChannel;
  10. import io.netty.handler.codec.http.HttpRequestDecoder;
  11. import io.netty.handler.codec.http.HttpResponseEncoder;
  12. public class HttpServer {
  13. public void start(int port) throws Exception {
  14. EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
  15. EventLoopGroup workerGroup = new NioEventLoopGroup();
  16. try {
  17. ServerBootstrap b = new ServerBootstrap(); // (2)
  18. b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) // (3)
  19. .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
  20. @Override
  21. public void initChannel(SocketChannel ch) throws Exception {
  22. // server端发送的是httpResponse,所以要使用HttpResponseEncoder进行编码
  23. ch.pipeline().addLast(new HttpResponseEncoder());
  24. // server端接收到的是httpRequest,所以要使用HttpRequestDecoder进行解码
  25. ch.pipeline().addLast(new HttpRequestDecoder());
  26. ch.pipeline().addLast(new HttpServerInboundHandler());
  27. }
  28. }).option(ChannelOption.SO_BACKLOG, 128) // (5)
  29. .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)
  30. ChannelFuture f = b.bind(port).sync(); // (7)
  31. f.channel().closeFuture().sync();
  32. } finally {
  33. workerGroup.shutdownGracefully();
  34. bossGroup.shutdownGracefully();
  35. }
  36. }
  37. public static void main(String[] args) throws Exception {
  38. HttpServer server = new HttpServer();
  39. server.start(8000);
  40. }
  41. }

2、HttpServerInboundHandler 解析客户端的请求,并进行响应

  1. package com.guowl.testhttpprotocol;
  2. import static io.netty.handler.codec.http.HttpHeaders.Names.CONNECTION;
  3. import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
  4. import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
  5. import static io.netty.handler.codec.http.HttpResponseStatus.OK;
  6. import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
  7. import io.netty.buffer.ByteBuf;
  8. import io.netty.buffer.Unpooled;
  9. import io.netty.channel.ChannelHandlerContext;
  10. import io.netty.channel.ChannelInboundHandlerAdapter;
  11. import io.netty.handler.codec.http.DefaultFullHttpResponse;
  12. import io.netty.handler.codec.http.FullHttpResponse;
  13. import io.netty.handler.codec.http.HttpContent;
  14. import io.netty.handler.codec.http.HttpHeaders;
  15. import io.netty.handler.codec.http.HttpHeaders.Values;
  16. import io.netty.handler.codec.http.HttpRequest;
  17. import org.slf4j.Logger;
  18. import org.slf4j.LoggerFactory;
  19. import com.guowl.utils.ByteBufToBytes;
  20. public class HttpServerInboundHandler extends ChannelInboundHandlerAdapter {
  21. private static Logger   logger  = LoggerFactory.getLogger(HttpServerInboundHandler.class);
  22. private ByteBufToBytes reader;
  23. @Override
  24. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  25. if (msg instanceof HttpRequest) {
  26. HttpRequest request = (HttpRequest) msg;
  27. System.out.println("messageType:" + request.headers().get("messageType"));
  28. System.out.println("businessType:" + request.headers().get("businessType"));
  29. if (HttpHeaders.isContentLengthSet(request)) {
  30. reader = new ByteBufToBytes((int) HttpHeaders.getContentLength(request));
  31. }
  32. }
  33. if (msg instanceof HttpContent) {
  34. HttpContent httpContent = (HttpContent) msg;
  35. ByteBuf content = httpContent.content();
  36. reader.reading(content);
  37. content.release();
  38. if (reader.isEnd()) {
  39. String resultStr = new String(reader.readFull());
  40. System.out.println("Client said:" + resultStr);
  41. FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer("I am ok"
  42. .getBytes()));
  43. response.headers().set(CONTENT_TYPE, "text/plain");
  44. response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
  45. response.headers().set(CONNECTION, Values.KEEP_ALIVE);
  46. ctx.write(response);
  47. ctx.flush();
  48. }
  49. }
  50. }
  51. @Override
  52. public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
  53. logger.info("HttpServerInboundHandler.channelReadComplete");
  54. ctx.flush();
  55. }
  56. }

3、HttpClient 向服务器发送请求

  1. package com.guowl.testhttpprotocol;
  2. import io.netty.bootstrap.Bootstrap;
  3. import io.netty.buffer.Unpooled;
  4. import io.netty.channel.ChannelFuture;
  5. import io.netty.channel.ChannelInitializer;
  6. import io.netty.channel.ChannelOption;
  7. import io.netty.channel.EventLoopGroup;
  8. import io.netty.channel.nio.NioEventLoopGroup;
  9. import io.netty.channel.socket.SocketChannel;
  10. import io.netty.channel.socket.nio.NioSocketChannel;
  11. import io.netty.handler.codec.http.DefaultFullHttpRequest;
  12. import io.netty.handler.codec.http.HttpHeaders;
  13. import io.netty.handler.codec.http.HttpMethod;
  14. import io.netty.handler.codec.http.HttpRequestEncoder;
  15. import io.netty.handler.codec.http.HttpResponseDecoder;
  16. import io.netty.handler.codec.http.HttpVersion;
  17. import java.net.URI;
  18. public class HttpClient {
  19. public void connect(String host, int port) throws Exception {
  20. EventLoopGroup workerGroup = new NioEventLoopGroup();
  21. try {
  22. Bootstrap b = new Bootstrap(); // (1)
  23. b.group(workerGroup); // (2)
  24. b.channel(NioSocketChannel.class); // (3)
  25. b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
  26. b.handler(new ChannelInitializer<SocketChannel>() {
  27. @Override
  28. public void initChannel(SocketChannel ch) throws Exception {
  29. // 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码
  30. ch.pipeline().addLast(new HttpResponseDecoder());
  31. // 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码
  32. ch.pipeline().addLast(new HttpRequestEncoder());
  33. ch.pipeline().addLast(new HttpClientInboundHandler());
  34. }
  35. });
  36. // Start the client.
  37. ChannelFuture f = b.connect(host, port).sync(); // (5)
  38. URI uri = new URI("http://127.0.0.1:8000");
  39. String msg = "Are you ok?";
  40. DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
  41. uri.toASCIIString(), Unpooled.wrappedBuffer(msg.getBytes()));
  42. // 构建http请求
  43. request.headers().set(HttpHeaders.Names.HOST, host);
  44. request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
  45. request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());
  46. request.headers().set("messageType", "normal");
  47. request.headers().set("businessType", "testServerState");
  48. // 发送http请求
  49. f.channel().write(request);
  50. f.channel().flush();
  51. f.channel().closeFuture().sync();
  52. } finally {
  53. workerGroup.shutdownGracefully();
  54. }
  55. }
  56. public static void main(String[] args) throws Exception {
  57. HttpClient client = new HttpClient();
  58. client.connect("127.0.0.1", 8000);
  59. }
  60. }

4、HttpClientInboundHandler 对服务器的响应进行读取

  1. package com.guowl.testhttpprotocol;
  2. import io.netty.buffer.ByteBuf;
  3. import io.netty.channel.ChannelHandlerContext;
  4. import io.netty.channel.ChannelInboundHandlerAdapter;
  5. import io.netty.handler.codec.http.HttpContent;
  6. import io.netty.handler.codec.http.HttpHeaders;
  7. import io.netty.handler.codec.http.HttpResponse;
  8. import com.guowl.utils.ByteBufToBytes;
  9. public class HttpClientInboundHandler extends ChannelInboundHandlerAdapter {
  10. private ByteBufToBytes reader;
  11. @Override
  12. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  13. if (msg instanceof HttpResponse) {
  14. HttpResponse response = (HttpResponse) msg;
  15. System.out.println("CONTENT_TYPE:" + response.headers().get(HttpHeaders.Names.CONTENT_TYPE));
  16. if (HttpHeaders.isContentLengthSet(response)) {
  17. reader = new ByteBufToBytes((int) HttpHeaders.getContentLength(response));
  18. }
  19. }
  20. if (msg instanceof HttpContent) {
  21. HttpContent httpContent = (HttpContent) msg;
  22. ByteBuf content = httpContent.content();
  23. reader.reading(content);
  24. content.release();
  25. if (reader.isEnd()) {
  26. String resultStr = new String(reader.readFull());
  27. System.out.println("Server said:" + resultStr);
  28. ctx.close();
  29. }
  30. }
  31. }
  32. }

5、ByteBufToBytes 读取NIO的工具类,可以一次性把ByteBuf的数据读取出来,也可以把多次ByteBuf中的数据统一读取出来。

  1. package com.guowl.utils;
  2. import io.netty.buffer.ByteBuf;
  3. import io.netty.buffer.Unpooled;
  4. public class ByteBufToBytes {
  5. private ByteBuf temp;
  6. private boolean end = true;
  7. public ByteBufToBytes(int length) {
  8. temp = Unpooled.buffer(length);
  9. }
  10. public void reading(ByteBuf datas) {
  11. datas.readBytes(temp, datas.readableBytes());
  12. if (this.temp.writableBytes() != 0) {
  13. end = false;
  14. } else {
  15. end = true;
  16. }
  17. }
  18. public boolean isEnd() {
  19. return end;
  20. }
  21. public byte[] readFull() {
  22. if (end) {
  23. byte[] contentByte = new byte[this.temp.readableBytes()];
  24. this.temp.readBytes(contentByte);
  25. this.temp.release();
  26. return contentByte;
  27. } else {
  28. return null;
  29. }
  30. }
  31. public byte[] read(ByteBuf datas) {
  32. byte[] bytes = new byte[datas.readableBytes()];
  33. datas.readBytes(bytes);
  34. return bytes;
  35. }
  36. }

注意事项:

1、可以通过在Netty的Chanel中发送HttpRequest对象,完成发送http请求的要求,同时可以对HttpHeader进行设置。

2、可以通过HttpResponse发送http响应,同时可以对HttpHeader进行设置。

3、上面涉及到的http对象都是Netty自己封装的,不是标准的。

Netty4.0学习笔记系列之三:构建简单的http服务(转)的更多相关文章

  1. Netty4.0学习笔记系列之一:Server与Client的通讯

    http://blog.csdn.net/u013252773/article/details/21046697 本文是学习Netty的第一篇文章,主要对Netty的Server和Client间的通讯 ...

  2. Netty4.0学习笔记系列之二:Handler的执行顺序(转)

    http://blog.csdn.net/u013252773/article/details/21195593 Handler在netty中,无疑占据着非常重要的地位.Handler与Servlet ...

  3. Netty4.0学习笔记系列之四:混合使用coder和handler

    Handler如何使用在前面的例子中已经有了示范,那么同样是扩展自ChannelHandler的Encoder和Decoder,与Handler混合后又是如何使用的?本文将通过一个实际的小例子来展示它 ...

  4. Netty4.0学习笔记系列之二:Handler的执行顺序

    Handler在netty中,无疑占据着非常重要的地位.Handler与Servlet中的filter很像,通过Handler可以完成通讯报文的解码编码.拦截指定的报文.统一对日志错误进行处理.统一对 ...

  5. WebService学习笔记系列(二)

    soap(简单对象访问协议),它是在http基础之上传递xml格式数据的协议.soap协议分为两个版本,soap1.1和soap1.2. 在学习webservice时我们有一个必备工具叫做tcpmon ...

  6. .NET CORE学习笔记系列(2)——依赖注入【1】控制反转IOC

    原文:https://www.cnblogs.com/artech/p/net-core-di-01.html 一.流程控制的反转 IoC的全名Inverse of Control,翻译成中文就是“控 ...

  7. DirectX 总结和DirectX 9.0 学习笔记

    转自:http://www.cnblogs.com/graphics/archive/2009/11/25/1583682.html DirectX 总结 DDS DirectXDraw Surfac ...

  8. 步步为营 SharePoint 开发学习笔记系列总结

    转:http://www.cnblogs.com/springyangwc/archive/2011/08/03/2126763.html 概要 为时20多天的sharepoint开发学习笔记系列终于 ...

  9. .NET CORE学习笔记系列(2)——依赖注入[6]: .NET Core DI框架[编程体验]

    原文https://www.cnblogs.com/artech/p/net-core-di-06.html 毫不夸张地说,整个ASP.NET Core框架是建立在一个依赖注入框架之上的,它在应用启动 ...

随机推荐

  1. android 35 ListView增删改差

    MainActivity package com.sxt.day05_11; import java.util.ArrayList; import java.util.List; import and ...

  2. iOS-本地推送(本地通知)

    第一步:注册本地通知: // 设置本地通知 + (void)registerLocalNotification:(NSInteger)alertTime { UILocalNotification * ...

  3. Google技术专家的建议:各种SdkVersion如何选择?

    原文链接: https://medium.com/google-developers/picking-your-compilesdkversion-minsdkversion-targetsdkver ...

  4. RxJava使用场景小结

    一.Scheduler线程切换 这种场景经常会在“后台线程取数据,主线程展示”的模式中看见 Observable.just(1, 2, 3, 4) .subscribeOn(Schedulers.io ...

  5. common-lang——StringUtils

    1.文字省略处理 最多显示几个字 StringUtils.abbreviate("中华人民共和国", 5); // output:中华.. 2.文字中间省略 最多显示几个字符 St ...

  6. NUll在oracle与sqlserver中使用相同与区别

    最近在使用Oracle进行开发,遇到很多与以前使用sqlserver的不同语法.今天遇到null在两种数据库上面操作上的差别,在此记录两种数据库上的差异. null 与字符串相加 1.在oracle中 ...

  7. Ant学习笔记(2) 在Eclipse中使用Ant

    Eclipse默认提供了对Ant的支持,在Eclipse中不需要安装任何插件就能直接编辑和运行Ant.Eclipse中包含了一个Ant脚本编辑器,Ant脚本编辑器提供了对Ant脚本的语法搞来高亮.自动 ...

  8. ASP.NET Boilerplate Castle容器无缝添加日志功能

    以添加log4net日志框架为例进行讲解 1.通常log4net的配置参数放在单独的配置文件中,但也可以写在web.config中,这里在我们的web项目中添加log4net.config应用配置文件 ...

  9. Word 中标题的编号变成黑框

    问题: 在使用Word编写文档时,提前拟好的标题编号会突然变成黑框(黑色的方框,黑色的矩形),如下图 解决方案: 1.将光标定位到标题中,紧邻黑框的右侧 2.按键盘左方向键使方框变成黑色 4.按键盘的 ...

  10. 在eclipse下面搭建Clojure开发运行环境

    打开eclipse,点击菜单栏“help->Install New Software...", 然后,点击”add“, 在Location处输入 http://ccw.cgrand.n ...