netty httpserver

netty也可以作为一个小巧的http服务器使用。

 1 package com.ming.netty.http.httpserver;
 2
 3 import java.net.InetSocketAddress;
 4
 5 import io.netty.bootstrap.ServerBootstrap;
 6 import io.netty.channel.ChannelFuture;
 7 import io.netty.channel.ChannelInitializer;
 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.HttpContentCompressor;
12 import io.netty.handler.codec.http.HttpObjectAggregator;
13 import io.netty.handler.codec.http.HttpRequestDecoder;
14 import io.netty.handler.codec.http.HttpResponseDecoder;
15 import io.netty.handler.stream.ChunkedWriteHandler;
16
17 public class HttpServer {
18
19     public static void main(String[] args) {
20         new HttpServer().run("127.0.0.1", 8500);
21     }
22
23
24     public void run(String addr,int port){
25         NioEventLoopGroup boosGroup=new NioEventLoopGroup();
26         NioEventLoopGroup workGroup=new NioEventLoopGroup();
27         try {
28             ServerBootstrap bootstrap=new ServerBootstrap();
29             bootstrap.group(boosGroup, workGroup);
30             bootstrap.channel(NioServerSocketChannel.class);
31             bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
32
33                 @Override
34                 protected void initChannel(SocketChannel ch) throws Exception {
35                     ch.pipeline().addLast("http-decoder",new HttpRequestDecoder());
36                     ch.pipeline().addLast("http-aggregator",new HttpObjectAggregator(65536));//定义缓冲数据量
37                     ch.pipeline().addLast("encoder", new HttpResponseDecoder());
38                     ch.pipeline().addLast("chunkedWriter", new ChunkedWriteHandler());
39                     ch.pipeline().addLast("deflater", new HttpContentCompressor());//压缩作用
40                     ch.pipeline().addLast("handler", new HttpServerHandler());
41                 }
42
43             });
44              ChannelFuture f=bootstrap.bind(new InetSocketAddress(addr, port)).sync();
45               System.out.println("启动服务器:"+f.channel().localAddress());
46               //等等服务器端监听端口关闭
47               f.channel().closeFuture().sync();
48         } catch (Exception e) {
49             e.printStackTrace();
50         }finally{
51              workGroup.shutdownGracefully();
52              workGroup.shutdownGracefully();
53         }
54     }
55
56
57 }
  1 package com.ming.netty.http.httpserver;
  2
  3 import java.nio.ByteBuffer;
  4 import java.util.Map;
  5
  6 import io.netty.buffer.ByteBuf;
  7 import io.netty.buffer.Unpooled;
  8 import io.netty.buffer.UnpooledByteBufAllocator;
  9 import io.netty.channel.Channel;
 10 import io.netty.channel.ChannelFutureListener;
 11 import io.netty.channel.ChannelHandlerContext;
 12 import io.netty.channel.SimpleChannelInboundHandler;
 13 import io.netty.handler.codec.http.DefaultFullHttpRequest;
 14 import io.netty.handler.codec.http.DefaultFullHttpResponse;
 15 import io.netty.handler.codec.http.FullHttpResponse;
 16 import io.netty.handler.codec.http.HttpContent;
 17 import io.netty.handler.codec.http.HttpHeaders;
 18 import io.netty.handler.codec.http.HttpMessage;
 19 import io.netty.handler.codec.http.HttpRequest;
 20 import io.netty.handler.codec.http.HttpResponseStatus;
 21 import io.netty.handler.codec.http.HttpVersion;
 22 import io.netty.handler.codec.http.LastHttpContent;
 23 import io.netty.util.CharsetUtil;
 24
 25 public class HttpServerHandler  extends SimpleChannelInboundHandler<Object> {
 26
 27     private HttpRequest request;
 28
 29     private ByteBuf buffer_body = UnpooledByteBufAllocator.DEFAULT.buffer();
 30
 31     private StringBuffer sb_debug = new StringBuffer();
 32
 33     @Override
 34     protected void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
 35         DefaultFullHttpRequest request=(DefaultFullHttpRequest)msg;
 36
 37         System.out.println("启动服务器:"+request.getMethod()+request.getUri());
 38          try {
 39               if ((msg instanceof HttpMessage) && HttpHeaders.is100ContinueExpected((HttpMessage)msg)) {
 40                 ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
 41               }
 42               if (msg instanceof HttpRequest) {
 43                 this.request = (HttpRequest)msg;
 44                 sb_debug.append("\n>> HTTP REQUEST -----------\n");
 45                 sb_debug.append(this.request.getProtocolVersion().toString())
 46                     .append(" ").append(this.request.getMethod().name())
 47                     .append(" ").append(this.request.getUri());
 48                 sb_debug.append("\n");
 49                 HttpHeaders headers = this.request.headers();
 50                 if (!headers.isEmpty()) {
 51                   for (Map.Entry<String, String> header : headers) {
 52                     sb_debug.append(header.getKey()).append(": ").append(header.getValue()).append("\n");
 53                   }
 54                 }
 55                 sb_debug.append("\n");
 56               } else if (msg instanceof HttpContent) {
 57                 HttpContent content = (HttpContent) msg;
 58                 ByteBuf thisContent = content.content();
 59                 if (thisContent.isReadable()) {
 60                   buffer_body.writeBytes(thisContent);
 61                 }
 62                 if (msg instanceof LastHttpContent) {
 63                   sb_debug.append(buffer_body.toString(CharsetUtil.UTF_8));
 64                   LastHttpContent trailer = (LastHttpContent) msg;
 65                   if (!trailer.trailingHeaders().isEmpty()) {
 66                     for (String name : trailer.trailingHeaders().names()) {
 67                       sb_debug.append(name).append("=");
 68                       for (String value : trailer.trailingHeaders().getAll(name)) {
 69                         sb_debug.append(value).append(",");
 70                       }
 71                       sb_debug.append("\n\n");
 72                     }
 73                   }
 74                   sb_debug.append("\n<< HTTP REQUEST -----------");
 75                 }
 76               }
 77             } catch (Exception e) {
 78               e.printStackTrace();
 79             } finally {
 80                 System.out.println(sb_debug+"");
 81                 FullHttpResponse  response=new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.ACCEPTED);
 82                 String str="hello,my netty httpServer!";
 83                 StringBuilder buf=new StringBuilder();
 84                 buf.append("<!DOCTYPE html><head></head><body>").append(str).append("</body></html>");
 85                 ByteBuf buffer=Unpooled.copiedBuffer(buf,CharsetUtil.UTF_8);
 86                 response.content().writeBytes(buffer);
 87                 response.headers().set("Content-Type", "text/html; charset=UTF-8");
 88                 response.headers().set("Content-Length",1000);
 89                 buffer.release();
 90                 ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
 91
 92
 93             }
 94     }
 95
 96
 97
 98
 99
100
101
102 }
时间: 2024-08-26 06:30:19

netty httpserver的相关文章

(中级篇 NettyNIO编解码开发)第十章-Http协议开发应用(基于Netty的HttpServer和HttpClient的简单实现)

1.HttpServer 1 package nettyHttpTest; 2 3 4 5 import io.netty.bootstrap.ServerBootstrap; 6 import io.netty.channel.ChannelFuture; 7 import io.netty.channel.ChannelInitializer; 8 import io.netty.channel.ChannelOption; 9 import io.netty.channel.EventLo

使用Netty实现HttpServer

package netty; import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION; import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH; import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE; import static io.ne

netty高级篇(3)-HTTP协议开发

一.HTTP协议简介 应用层协议http,发展至今已经是http2.0了,拥有以下特点: (1) CS模式的协议 (2) 简单 - 只需要服务URL,携带必要的请求参数或者消息体 (3) 灵活 - 任意类型,传输内容类型由HTTP消息头中的Content-Type加以标记 (4) 无状态 - 必须借助额外手段,比如session或者cookie来保持状态 1.1 HTTP请求消息(HttpRequest) 客户端发送一个HTTP请求到服务器的请求消息包括以下格式:请求行(request line

Netty In Action中国版 - 第二章:第一Netty程序

本章介绍 获得Netty4最新的版本号 设置执行环境,以构建和执行netty程序 创建一个基于Netty的server和client 拦截和处理异常 编制和执行Nettyserver和client 本章将简介Netty的核心概念,这个狠心概念就是学习Netty是怎样拦截和处理异常.对于刚開始学习netty的读者.利用netty的异常拦截机制来调试程序问题非常有帮助.本章还会介绍其它一些核心概念.如server和client的启动以及分离通道的处理程序.本章学习一些基础以便后面章节的深入学习. 本

Mina、Netty、Twisted一起学(五):整合protobuf

protobuf是谷歌的Protocol Buffers的简称,用于结构化数据和字节码之间互相转换(序列化.反序列化),一般应用于网络传输,可支持多种编程语言. protobuf怎样使用这里不再介绍,本文主要介绍在MINA.Netty.Twisted中怎样使用protobuf,不了解protobuf的同学能够去參考我的还有一篇博文. 在前面的一篇博文中.有介绍到一种用一个固定为4字节的前缀Header来指定Body的字节数的一种消息切割方式.在这里相同要使用到. 仅仅是当中Body的内容不再是字

Mina、Netty、Twisted一起学(十):线程模型

要想开发一个高性能的TCPserver,熟悉所使用框架的线程模型非常重要.MINA.Netty.Twisted本身都是高性能的网络框架,假设再搭配上高效率的代码.才干实现一个高大上的server. 可是假设不了解它们的线程模型.就非常难写出高性能的代码.框架本身效率再高.程序写的太差,那么server总体的性能也不会太高.就像一个电脑,CPU再好.内存小硬盘慢散热差,总体的性能也不会太高. 玩过Android开发的同学会知道,在Android应用中有一个非常重要线程:UI线程(即主线程). UI

【游戏开发】Netty TCP粘包/拆包问题的解决办法(二)

上一篇:[Netty4.X]Unity客户端与Netty服务器的网络通信(一) 一.什么是TCP粘包/拆包 如图所示,假如客户端分别发送两个数据包D1和D2给服务端,由于服务端一次读取到的字节数是不确定的,故可能存在以下4中情况: 第一种情况:Server端分别读取到D1和D2,没有产生粘包和拆包的情况. 第二种情况:Server端一次接收到两个数据包,D1和D2粘合在一起,被称为TCP粘包. 第三种情况:Server端分2次读取到2个数据包,第一次读取到D1包和D2包的部分内容D2_1,第二次

netty与websocket通信demo

netty v3.9.4 websocket建立前,客户端需要与服务器进行握手 确认websocket连接,也就是说在处理websocket请求前,必需要处理一些http请求. websocket到现在为止,已经有多个版本,netty有相应的对应类,这部分处理一般不需要人工干预. 如果运行正常的话,会在页面的文本框中显示1-20记数. 可以通过firefox或chrome的开发人员工具,显看浏览器与服务器的交互. 主要是HttpServerChannelHandler2,加了些注释和少量debu

基于Netty4的HttpServer和HttpClient的简单实现

Netty的主页:http://netty.io/index.html 使用的Netty的版本:netty-4.0.23.Final.tar.bz2 ‐ 15-Aug-2014 (Stable, Recommended) 实现一个简单的Http请求及响应过程: 1.Client向Server发送http请求. 2.Server端对http请求进行解析. 3.Server端向client发送http响应. 4.Client对http响应进行解析. Http Server: package com.