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

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

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

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

    3、HttpClient 向服务器发送请求

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

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

    [java] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. package com.guowl.testhttpprotocol;  
    2.   
    3. import io.netty.buffer.ByteBuf;  
    4. import io.netty.channel.ChannelHandlerContext;  
    5. import io.netty.channel.ChannelInboundHandlerAdapter;  
    6. import io.netty.handler.codec.http.HttpContent;  
    7. import io.netty.handler.codec.http.HttpHeaders;  
    8. import io.netty.handler.codec.http.HttpResponse;  
    9.   
    10. import com.guowl.utils.ByteBufToBytes;  
    11.   
    12. public class HttpClientInboundHandler extends ChannelInboundHandlerAdapter {  
    13.     private ByteBufToBytes reader;  
    14.   
    15.     @Override  
    16.     public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {  
    17.         if (msg instanceof HttpResponse) {  
    18.             HttpResponse response = (HttpResponse) msg;  
    19.             System.out.println("CONTENT_TYPE:" + response.headers().get(HttpHeaders.Names.CONTENT_TYPE));  
    20.             if (HttpHeaders.isContentLengthSet(response)) {  
    21.                 reader = new ByteBufToBytes((int) HttpHeaders.getContentLength(response));  
    22.             }  
    23.         }  
    24.   
    25.         if (msg instanceof HttpContent) {  
    26.             HttpContent httpContent = (HttpContent) msg;  
    27.             ByteBuf content = httpContent.content();  
    28.             reader.reading(content);  
    29.             content.release();  
    30.   
    31.             if (reader.isEnd()) {  
    32.                 String resultStr = new String(reader.readFull());  
    33.                 System.out.println("Server said:" + resultStr);  
    34.                   
    35.                 ctx.close();  
    36.             }  
    37.         }  
    38.     }  
    39.   
    40. }  

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

    [java] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. package com.guowl.utils;  
    2.   
    3. import io.netty.buffer.ByteBuf;  
    4. import io.netty.buffer.Unpooled;  
    5.   
    6. public class ByteBufToBytes {  
    7.     private ByteBuf temp;  
    8.   
    9.     private boolean end = true;  
    10.   
    11.     public ByteBufToBytes(int length) {  
    12.         temp = Unpooled.buffer(length);  
    13.     }  
    14.   
    15.     public void reading(ByteBuf datas) {  
    16.         datas.readBytes(temp, datas.readableBytes());  
    17.         if (this.temp.writableBytes() != 0) {  
    18.             end = false;  
    19.         } else {  
    20.             end = true;  
    21.         }  
    22.     }  
    23.   
    24.     public boolean isEnd() {  
    25.         return end;  
    26.     }  
    27.   
    28.     public byte[] readFull() {  
    29.         if (end) {  
    30.             byte[] contentByte = new byte[this.temp.readableBytes()];  
    31.             this.temp.readBytes(contentByte);  
    32.             this.temp.release();  
    33.             return contentByte;  
    34.         } else {  
    35.             return null;  
    36.         }  
    37.     }  
    38.   
    39.     public byte[] read(ByteBuf datas) {  
    40.         byte[] bytes = new byte[datas.readableBytes()];  
    41.         datas.readBytes(bytes);  
    42.         return bytes;  
    43.     }  
    44. }  

    注意事项:

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

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

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

  • 相关阅读:
    loushang框架的开发中关于BSP的使用,将写好的功能模块部署到主页界面结构上
    浪潮“楼上”开发平台简介
    New博客园新的开始!
    python相关
    day20 函数闭包与装饰器
    计算机基础
    day19 生成器函数
    简历
    day18 迭代器
    数据库基础(代码)
  • 原文地址:https://www.cnblogs.com/jiligalaer/p/3972531.html
Copyright © 2020-2023  润新知