{"id":4124,"date":"2018-10-15T21:18:05","date_gmt":"2018-10-15T13:18:05","guid":{"rendered":"https:\/\/ixyzero.com\/blog\/?p=4124"},"modified":"2018-10-15T21:18:05","modified_gmt":"2018-10-15T13:18:05","slug":"netty-http%e6%9c%8d%e5%8a%a1%e7%9a%84%e5%ae%9e%e7%8e%b0%e6%a0%b7%e4%be%8b","status":"publish","type":"post","link":"https:\/\/ixyzero.com\/blog\/archives\/4124.html","title":{"rendered":"Netty HTTP\u670d\u52a1\u7684\u5b9e\u73b0\u6837\u4f8b"},"content":{"rendered":"<p>=Start=<\/p>\n<h4 id=\"id-\u6a21\u677f-\u7f18\u7531\uff1a\">\u7f18\u7531\uff1a<\/h4>\n<p>Netty \u662f\u4e00\u4e2a\u9ad8\u6027\u80fd\u3001\u5f02\u6b65\u4e8b\u4ef6\u9a71\u52a8\u7684 NIO \u6846\u67b6\u3002\u5728\u5b66\u4e60 Netty \u7684\u65f6\u5019\uff0c\u53d1\u73b0 Netty \u4e5f\u53ef\u4ee5\u5b9e\u73b0HTTP\u670d\u52a1\uff0c\u4e8e\u662f\u628a\u5b66\u4e60\u7684\u8fc7\u7a0b\u8bb0\u5f55\u6574\u7406\u4e00\u4e0b\u5f62\u6210\u4e00\u7bc7\u6587\u7ae0\uff0c\u65b9\u4fbf\u4ee5\u540e\u53c2\u8003\u3002<\/p>\n<h4 id=\"id-\u6a21\u677f-\u6b63\u6587\uff1a\">\u6b63\u6587\uff1a<\/h4>\n<h5 id=\"id-\u6a21\u677f-\u53c2\u8003\u89e3\u7b54\uff1a\">\u53c2\u8003\u89e3\u7b54\uff1a<\/h5>\n<p>\u6240\u6709\u7684 Netty \u670d\u52a1\u5668\u90fd\u9700\u8981\u4ee5\u4e0b2\u4e2a\u90e8\u5206\uff1a<\/p>\n<ol>\n<li>ServerBootstrap \uff1a\u8fd9\u662f\u914d\u7f6e\u670d\u52a1\u5668\u7684<span style=\"color: #ff0000;\"><strong>\u542f\u52a8\u4ee3\u7801<\/strong><\/span>\u3002\u5b83\u4f1a\u5c06\u670d\u52a1\u5668\u7ed1\u5b9a\u5230\u5b83\u8981\u76d1\u542c\u8fde\u63a5\u8bf7\u6c42\u7684\u7aef\u53e3\u4e0a\uff1b<\/li>\n<li>\u81f3\u5c11\u4e00\u4e2a ChannelHandler \uff1a\u8be5\u7ec4\u4ef6\u5b9e\u73b0\u4e86\u670d\u52a1\u5668\u5bf9\u4ece\u5ba2\u6237\u7aef\u63a5\u6536\u7684\u6570\u636e\u7684\u5904\u7406\uff0c\u5373\u5b83\u7684<span style=\"color: #ff0000;\"><strong>\u4e1a\u52a1\u903b\u8f91<\/strong><\/span>\u3002<\/li>\n<\/ol>\n<hr \/>\n<p>\u8fd9\u91cc\u5c06Netty\u670d\u52a1\u5668\u653e\u5728\u4e863\u4e2aclass\u4e2d\uff0c\u5206\u522b\u662f\uff1a<\/p>\n<ol>\n<li>NettyServer #\u521b\u5efaServerBootstrap\u7528\u4e8e\u5f15\u5bfc\u670d\u52a1\u5668<\/li>\n<li>NettyServerChannel #\u65b0\u5efachannel\u5e76\u7528handler\u8fdb\u884c\u521d\u59cb\u5316\uff08\u53ef\u7b80\u5316\u653e\u5728NettyServer\u4e2d\uff09<\/li>\n<li>NettyServerHandler #\u901a\u8fc7\u8986\u5199\u90e8\u5206\u65b9\u6cd5\u5b9e\u73b0\u5177\u4f53\u7684\u4e1a\u52a1\u903b\u8f91<\/li>\n<\/ol>\n<hr \/>\n<p>Netty\u670d\u52a1\u5668\u7684\u5f15\u5bfc\u8fc7\u7a0b\uff1a<\/p>\n<ul>\n<li>\u521b\u5efa ServerBootstrap \u7684\u5b9e\u4f8b\u6765\u5f15\u5bfc\u548c\u7ed1\u5b9a\u670d\u52a1\u5668\u3002<\/li>\n<li><strong>\u521b\u5efa NioEventLoopGroup \u8fdb\u884c\u4e8b\u4ef6\u7684\u5904\u7406\uff0c\u5305\u62ec\u63a5\u6536\u65b0\u7684\u8fde\u63a5\uff0c\u5904\u7406\u8bfb\u5199<\/strong>\u3002<\/li>\n<li>\u4f7f\u7528<strong>\u540c\u4e00\u4e2aNettyServerHandler\u5b9e\u4f8b\u521d\u59cb\u5316\u6bcf\u4e00\u4e2a\u65b0\u7684Channel<\/strong>\u3002<\/li>\n<li>bind()\u7ed1\u5b9a\u670d\u52a1\u5668\u7aef\u53e3\u8fdb\u884c\u76d1\u542c\u3002<\/li>\n<\/ul>\n<pre class=\"lang:default decode:true\">package com.ixyzero.learn.netty;\r\n\r\nimport io.netty.bootstrap.ServerBootstrap;\r\nimport io.netty.channel.ChannelFuture;\r\nimport io.netty.channel.EventLoopGroup;\r\nimport io.netty.channel.nio.NioEventLoopGroup;\r\nimport io.netty.channel.socket.nio.NioServerSocketChannel;\r\n\r\npublic class NettyServer {\r\n    private static final int port = 8081; \/\/\u8bbe\u7f6e\u670d\u52a1\u76d1\u542c\u7aef\u53e3\r\n    private static  ServerBootstrap b = new ServerBootstrap();\r\n    private static  EventLoopGroup group = new NioEventLoopGroup();   \/\/ \u901a\u8fc7NIO\u65b9\u5f0f\u6765\u63a5\u6536\u8fde\u63a5\u548c\u5904\u7406\u8fde\u63a5\r\n\r\n    \/**\r\n     * Netty\u521b\u5efa\u5168\u90e8\u90fd\u662f\u5b9e\u73b0\u81ea AbstractBootstrap\u3002\r\n     * \u5ba2\u6237\u7aef\u7684\u662f Bootstrap\uff0c\u670d\u52a1\u7aef\u7684\u5219\u662f ServerBootstrap\u3002\r\n     **\/\r\n    public static void main(String[] args) throws InterruptedException {\r\n        try {\r\n            b.group(group);\r\n            b.channel(NioServerSocketChannel.class);\r\n            b.childHandler(new NettyServerChannel()); \/\/\u4e3a\u65b0\u7684\u8fde\u63a5\u521b\u5efa\u65b0\u7684channel\r\n            \/\/ \u670d\u52a1\u5668\u7ed1\u5b9a\u7aef\u53e3\u76d1\u542c\r\n            ChannelFuture f = b.bind(port).sync();\r\n            System.out.println(\"\u670d\u52a1\u7aef\u542f\u52a8\u6210\u529f,\u7aef\u53e3\u662f: \"+port);\r\n            \/\/ \u76d1\u542c\u670d\u52a1\u5668\u5173\u95ed\u76d1\u542c\r\n            f.channel().closeFuture().sync();\r\n        } finally {\r\n            group.shutdownGracefully(); \/\/\u5173\u95edEventLoopGroup\uff0c\u91ca\u653e\u6389\u6240\u6709\u8d44\u6e90\u5305\u62ec\u521b\u5efa\u7684\u7ebf\u7a0b\r\n        }\r\n    }\r\n}<\/pre>\n<p>&amp;<\/p>\n<p>\u5728\u4e0a\u9762\u7684NettyServer.java\u91cc\u6709\u4e00\u4e2achildHandler()\u8c03\u7528\uff0c\u7528\u4e8e\u6dfb\u52a0 NettyServerHandler \u5230 Channel \u7684 ChannelPipeline \uff0c\u662f\u901a\u8fc7\u65b0\u5efa\u8fd9\u91cc\u7684 NettyServerChannel \u7c7b\uff08\u7ee7\u627f\u81eaChannelInitializer\uff09\u5b9e\u73b0\u7684\u3002<\/p>\n<pre class=\"lang:default decode:true \">package com.ixyzero.learn.netty;\r\n\r\nimport io.netty.channel.ChannelInitializer;\r\nimport io.netty.channel.ChannelPipeline;\r\nimport io.netty.channel.socket.SocketChannel;\r\nimport io.netty.handler.codec.http.HttpObjectAggregator;\r\nimport io.netty.handler.codec.http.HttpRequestDecoder;\r\nimport io.netty.handler.codec.http.HttpResponseEncoder;\r\n\r\npublic class NettyServerChannel extends ChannelInitializer&lt;SocketChannel&gt; {\r\n\r\n    @Override\r\n    protected void initChannel(SocketChannel ch) throws Exception {\r\n        ChannelPipeline ph = ch.pipeline();\r\n        \/\/\u5904\u7406http\u670d\u52a1\u7684\u5173\u952ehandler\r\n        ph.addLast(\"encoder\",new HttpResponseEncoder());\r\n        ph.addLast(\"decoder\",new HttpRequestDecoder());\r\n        ph.addLast(\"aggregator\", new HttpObjectAggregator(10*1024*1024));\r\n        ph.addLast(\"handler\", new NettyServerHandler());\/\/ \u670d\u52a1\u7aef\u4e1a\u52a1\u903b\u8f91\r\n    }\r\n}<\/pre>\n<p>&amp;<\/p>\n<p>\u7531\u4e8e\u6211\u4eec\u7684\u6837\u4f8b\u5f88\u7b80\u5355\uff0c\u53ea\u9700\u8981\u7ee7\u627f ChannelInboundHandlerAdapter \u5c31\u884c\u4e86\u3002\u8fd9\u4e2a\u7c7b\u63d0\u4f9b\u4e86\u9ed8\u8ba4 ChannelInboundHandler \u7684\u5b9e\u73b0\uff0c\u6240\u4ee5\u53ea\u9700\u8981\u90e8\u5206\u8986\u5199\u4e0b\u9762\u7684\u65b9\u6cd5\uff1a<\/p>\n<ul>\n<li>channelRead() &#8211; \u6bcf\u4e2a\u4fe1\u606f\u5165\u7ad9\u90fd\u4f1a\u8c03\u7528\uff1b<\/li>\n<li>channelReadComplete() &#8211; \u901a\u77e5\u5904\u7406\u5668\u6700\u540e\u7684 channelread() \u662f\u5f53\u524d\u6279\u5904\u7406\u4e2d\u7684\u6700\u540e\u4e00\u6761\u6d88\u606f\u65f6\u8c03\u7528\uff1b<\/li>\n<li>exceptionCaught()- \u8bfb\u64cd\u4f5c\u65f6\u6355\u83b7\u5230\u5f02\u5e38\u65f6\u8c03\u7528\uff1b<\/li>\n<\/ul>\n<pre class=\"lang:default decode:true \">package com.ixyzero.learn.netty;\r\n\r\nimport io.netty.buffer.ByteBuf;\r\nimport io.netty.buffer.Unpooled;\r\nimport io.netty.channel.ChannelFutureListener;\r\nimport io.netty.channel.ChannelHandlerContext;\r\nimport io.netty.channel.ChannelInboundHandlerAdapter;\r\nimport io.netty.handler.codec.http.DefaultFullHttpResponse;\r\nimport io.netty.handler.codec.http.FullHttpRequest;\r\nimport io.netty.handler.codec.http.FullHttpResponse;\r\nimport io.netty.handler.codec.http.HttpHeaderNames;\r\nimport io.netty.handler.codec.http.HttpMethod;\r\nimport io.netty.handler.codec.http.HttpResponseStatus;\r\nimport io.netty.handler.codec.http.HttpVersion;\r\nimport io.netty.util.CharsetUtil;\r\nimport java.net.InetAddress;\r\n\r\npublic class NettyServerHandler extends ChannelInboundHandlerAdapter {\r\n    private String result=\"\";\r\n    \/*\r\n     * \u6536\u5230\u6d88\u606f\u65f6\uff0c\u8fd4\u56de\u4fe1\u606f\r\n     *\/\r\n    @Override\r\n    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {\r\n        if(! (msg instanceof FullHttpRequest)){\r\n            result = \"\u672a\u77e5\u8bf7\u6c42!\";\r\n            System.out.println(\"msg not FullHttpRequest\");\r\n            send(ctx, result, HttpResponseStatus.BAD_REQUEST);\r\n            return;\r\n        }\r\n        FullHttpRequest httpRequest = (FullHttpRequest)msg;\r\n        try{\r\n            String path = httpRequest.uri();        \/\/\u83b7\u53d6\u8def\u5f84\r\n            System.out.println(\"URI: \" + path);\r\n\r\n            String body = getBody(httpRequest);     \/\/\u83b7\u53d6\u53c2\u6570\r\n            HttpMethod method = httpRequest.method();\/\/\u83b7\u53d6\u8bf7\u6c42\u65b9\u6cd5\r\n\r\n            \/\/\u5982\u679c\u4e0d\u662f\u8fd9\u4e2a\u8def\u5f84\uff0c\u5c31\u76f4\u63a5\u8fd4\u56de\u9519\u8bef\r\n            if(!\"\/test\".equalsIgnoreCase(path)){\r\n                result=\"\u975e\u6cd5\u8bf7\u6c42!\";\r\n                send(ctx, result, HttpResponseStatus.BAD_REQUEST);\r\n                return;\r\n            }\r\n            System.out.println(\"\u63a5\u6536\u5230:\"+method+\" \u8bf7\u6c42\");\r\n            \/\/\u5982\u679c\u662fGET\u8bf7\u6c42\r\n            if(HttpMethod.GET.equals(method)){\r\n                \/\/\u63a5\u53d7\u5230\u7684\u6d88\u606f\uff0c\u505a\u4e1a\u52a1\u903b\u8f91\u5904\u7406...\r\n                System.out.println(\"body:\"+body);\r\n                result=\"GET\u8bf7\u6c42\";\r\n                send(ctx, result, HttpResponseStatus.OK);\r\n                return;\r\n            }\r\n            \/\/\u5982\u679c\u662fPOST\u8bf7\u6c42\r\n            if(HttpMethod.POST.equals(method)){\r\n                \/\/\u63a5\u53d7\u5230\u7684\u6d88\u606f\uff0c\u505a\u4e1a\u52a1\u903b\u8f91\u5904\u7406...\r\n                System.out.println(\"body:\"+body);\r\n                result=\"POST\u8bf7\u6c42\";\r\n                send(ctx, result, HttpResponseStatus.OK);\r\n                return;\r\n            }\r\n\r\n            \/\/\u5982\u679c\u662fPUT\u8bf7\u6c42\r\n            if(HttpMethod.PUT.equals(method)){\r\n                \/\/\u63a5\u53d7\u5230\u7684\u6d88\u606f\uff0c\u505a\u4e1a\u52a1\u903b\u8f91\u5904\u7406...\r\n                System.out.println(\"body:\"+body);\r\n                result=\"PUT\u8bf7\u6c42\";\r\n                send(ctx, result, HttpResponseStatus.OK);\r\n                return;\r\n            }\r\n            \/\/\u5982\u679c\u662fDELETE\u8bf7\u6c42\r\n            if(HttpMethod.DELETE.equals(method)){\r\n                \/\/\u63a5\u53d7\u5230\u7684\u6d88\u606f\uff0c\u505a\u4e1a\u52a1\u903b\u8f91\u5904\u7406...\r\n                System.out.println(\"body:\"+body);\r\n                result=\"DELETE\u8bf7\u6c42\";\r\n                send(ctx, result, HttpResponseStatus.OK);\r\n                return;\r\n            }\r\n        }catch(Exception e){\r\n            System.out.println(\"\u5904\u7406\u8bf7\u6c42\u5931\u8d25!\");\r\n            e.printStackTrace();\r\n        }finally{\r\n            \/\/\u91ca\u653e\u8bf7\u6c42\r\n            httpRequest.release();\r\n        }\r\n    }\r\n\r\n    \/**\r\n     * \u83b7\u53d6body\u53c2\u6570\r\n     * @param request\r\n     * @return\r\n     *\/\r\n    private String getBody(FullHttpRequest request){\r\n        ByteBuf buf = request.content();\r\n        return buf.toString(CharsetUtil.UTF_8);\r\n    }\r\n\r\n    \/**\r\n     * \u53d1\u9001\u7684\u8fd4\u56de\u503c\r\n     * @param ctx\t  \u8fd4\u56de\r\n     * @param context \u6d88\u606f\r\n     * @param status \u72b6\u6001\r\n     *\/\r\n    private void send(ChannelHandlerContext ctx, String context,HttpResponseStatus status) {\r\n        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer(context, CharsetUtil.UTF_8));\r\n        response.headers().set(HttpHeaderNames.CONTENT_TYPE, \"text\/plain; charset=UTF-8\");\r\n        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);\r\n    }\r\n\r\n    \/*\r\n     * \u5efa\u7acb\u8fde\u63a5\u65f6\uff0c\u8fd4\u56de\u6d88\u606f\r\n     *\/\r\n    @Override\r\n    public void channelActive(ChannelHandlerContext ctx) throws Exception {\r\n        System.out.println(\"\u8fde\u63a5\u7684\u5ba2\u6237\u7aef\u5730\u5740:\" + ctx.channel().remoteAddress());\r\n        ctx.writeAndFlush(\"\u5ba2\u6237\u7aef\"+ InetAddress.getLocalHost().getHostName() + \"\u6210\u529f\u4e0e\u670d\u52a1\u7aef\u5efa\u7acb\u8fde\u63a5\uff01 \");\r\n        super.channelActive(ctx);\r\n    }\r\n}\r\n<\/pre>\n<p>&nbsp;<\/p>\n<h5 id=\"id-\u6a21\u677f-\u53c2\u8003\u94fe\u63a5\uff1a\">\u53c2\u8003\u94fe\u63a5\uff1a<\/h5>\n<ul>\n<li><a href=\"https:\/\/blog.csdn.net\/qazwsxpcm\/article\/details\/78364023\">Netty4 \u5b66\u4e60\u7b14\u8bb0\u4e4b\u56db: Netty HTTP\u670d\u52a1\u7684\u5b9e\u73b0<\/a>#<strong>\u4e3b\u8981\u53c2\u8003<\/strong><\/li>\n<li><a href=\"https:\/\/blog.csdn.net\/u013252773\/article\/details\/21195593\">Netty4.0\u5b66\u4e60\u7b14\u8bb0\u7cfb\u5217\u4e4b\u4e8c\uff1aHandler\u7684\u6267\u884c\u987a\u5e8f<\/a><\/li>\n<li><a href=\"https:\/\/doc.yonyoucloud.com\/doc\/essential-netty-in-action\/GETTING%20STARTED\/Writing%20the%20echo%20server.html\">\u5199\u4e00\u4e2a echo \u670d\u52a1\u5668<\/a><\/li>\n<li><a href=\"https:\/\/blog.csdn.net\/wangshuang1631\/article\/details\/73251180\">\u57fa\u4e8eNetty4\u6784\u5efaHTTP\u670d\u52a1&#8212;-\u6d4f\u89c8\u5668\u8bbf\u95ee\u548cNetty\u5ba2\u6237\u7aef\u8bbf\u95ee<\/a><\/li>\n<li><a href=\"https:\/\/emacsist.github.io\/2018\/05\/18\/%E5%9F%BA%E4%BA%8Enetty%E7%9A%84%E7%AE%80%E5%8D%95http%E6%9C%8D%E5%8A%A1%E4%BE%8B%E5%AD%90\/\">\u57fa\u4e8eNetty\u7684\u7b80\u5355HTTP\u670d\u52a1\u4f8b\u5b50<\/a><\/li>\n<li><a href=\"http:\/\/frobisher.me\/2017\/05\/30\/netty-echo-server\/\">Netty\u5b9e\u73b0Echo\u670d\u52a1\u5668\u548c\u5ba2\u6237\u7aef<\/a>#<strong>nice<\/strong><\/li>\n<li><a href=\"https:\/\/www.cnblogs.com\/crazylqy\/p\/4901820.html\">\uff08\u9ad8\u7ea7\u7bc7 Netty\u591a\u534f\u8bae\u5f00\u53d1\u548c\u5e94\u7528\uff09\u7b2c\u5341\u7ae0-Http\u534f\u8bae\u5f00\u53d1\u5e94\u7528\uff08\u57fa\u4e8eNetty\u7684HttpServer\u548cHttpClient\u7684\u7b80\u5355\u5b9e\u73b0\uff09<\/a><\/li>\n<li><a href=\"https:\/\/www.jianshu.com\/p\/cfd2c037dd7b\">netty\u7b80\u4ecb\u53caHTTP\u5b9e\u73b0Demo<\/a>#\u51e0\u4e2a\u603b\u7ed3\u4e0d\u9519<\/li>\n<li><a href=\"http:\/\/wiki.jikexueyuan.com\/project\/java-special-topic\/netty.html\">Netty \u7cfb\u5217\u4e4b Netty \u9ad8\u6027\u80fd\u4e4b\u9053<\/a><\/li>\n<\/ul>\n<p>=END=<\/p>\n","protected":false},"excerpt":{"rendered":"<p>=Start= \u7f18\u7531\uff1a Netty \u662f\u4e00\u4e2a\u9ad8\u6027\u80fd\u3001\u5f02\u6b65\u4e8b\u4ef6\u9a71\u52a8\u7684 NIO \u6846\u67b6\u3002\u5728\u5b66\u4e60 Netty \u7684\u65f6\u5019\uff0c\u53d1 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[23,7],"tags":[22,1206,1231,1230],"class_list":["post-4124","post","type-post","status-publish","format-standard","hentry","category-knowledgebase-2","category-programing","tag-http","tag-netty","tag-nioeventloopgroup","tag-serverbootstrap"],"views":3758,"_links":{"self":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/posts\/4124","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/comments?post=4124"}],"version-history":[{"count":1,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/posts\/4124\/revisions"}],"predecessor-version":[{"id":4125,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/posts\/4124\/revisions\/4125"}],"wp:attachment":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/media?parent=4124"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/categories?post=4124"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/tags?post=4124"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}