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

 package com.ming.netty.http.httpserver;

 import java.net.InetSocketAddress;

 import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
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.HttpContentCompressor;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseDecoder;
import io.netty.handler.stream.ChunkedWriteHandler; public class HttpServer { public static void main(String[] args) {
new HttpServer().run("127.0.0.1", 8500);
} public void run(String addr,int port){
NioEventLoopGroup boosGroup=new NioEventLoopGroup();
NioEventLoopGroup workGroup=new NioEventLoopGroup();
try {
ServerBootstrap bootstrap=new ServerBootstrap();
bootstrap.group(boosGroup, workGroup);
bootstrap.channel(NioServerSocketChannel.class);
bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast("http-decoder",new HttpRequestDecoder());
ch.pipeline().addLast("http-aggregator",new HttpObjectAggregator(65536));//定义缓冲数据量
ch.pipeline().addLast("encoder", new HttpResponseDecoder());
ch.pipeline().addLast("chunkedWriter", new ChunkedWriteHandler());
ch.pipeline().addLast("deflater", new HttpContentCompressor());//压缩作用
ch.pipeline().addLast("handler", new HttpServerHandler());
} });
ChannelFuture f=bootstrap.bind(new InetSocketAddress(addr, port)).sync();
System.out.println("启动服务器:"+f.channel().localAddress());
//等等服务器端监听端口关闭
f.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
}finally{
workGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
} }
 package com.ming.netty.http.httpserver;

 import java.nio.ByteBuffer;
import java.util.Map; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
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.HttpMessage;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.util.CharsetUtil; public class HttpServerHandler extends SimpleChannelInboundHandler<Object> { private HttpRequest request; private ByteBuf buffer_body = UnpooledByteBufAllocator.DEFAULT.buffer(); private StringBuffer sb_debug = new StringBuffer(); @Override
protected void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
DefaultFullHttpRequest request=(DefaultFullHttpRequest)msg; System.out.println("启动服务器:"+request.getMethod()+request.getUri());
try {
if ((msg instanceof HttpMessage) && HttpHeaders.is100ContinueExpected((HttpMessage)msg)) {
ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
}
if (msg instanceof HttpRequest) {
this.request = (HttpRequest)msg;
sb_debug.append("\n>> HTTP REQUEST -----------\n");
sb_debug.append(this.request.getProtocolVersion().toString())
.append(" ").append(this.request.getMethod().name())
.append(" ").append(this.request.getUri());
sb_debug.append("\n");
HttpHeaders headers = this.request.headers();
if (!headers.isEmpty()) {
for (Map.Entry<String, String> header : headers) {
sb_debug.append(header.getKey()).append(": ").append(header.getValue()).append("\n");
}
}
sb_debug.append("\n");
} else if (msg instanceof HttpContent) {
HttpContent content = (HttpContent) msg;
ByteBuf thisContent = content.content();
if (thisContent.isReadable()) {
buffer_body.writeBytes(thisContent);
}
if (msg instanceof LastHttpContent) {
sb_debug.append(buffer_body.toString(CharsetUtil.UTF_8));
LastHttpContent trailer = (LastHttpContent) msg;
if (!trailer.trailingHeaders().isEmpty()) {
for (String name : trailer.trailingHeaders().names()) {
sb_debug.append(name).append("=");
for (String value : trailer.trailingHeaders().getAll(name)) {
sb_debug.append(value).append(",");
}
sb_debug.append("\n\n");
}
}
sb_debug.append("\n<< HTTP REQUEST -----------");
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println(sb_debug+"");
FullHttpResponse response=new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.ACCEPTED);
String str="hello,my netty httpServer!";
StringBuilder buf=new StringBuilder();
buf.append("<!DOCTYPE html><head></head><body>").append(str).append("</body></html>");
ByteBuf buffer=Unpooled.copiedBuffer(buf,CharsetUtil.UTF_8);
response.content().writeBytes(buffer);
response.headers().set("Content-Type", "text/html; charset=UTF-8");
response.headers().set("Content-Length",1000);
buffer.release();
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
} }

netty httpserver的更多相关文章

  1. SpringCloud升级之路2020.0.x版-42.SpringCloudGateway 现有的可供分析的请求日志以及缺陷

    本系列代码地址:https://github.com/JoJoTec/spring-cloud-parent 网关由于是所有外部用户请求的入口,记录这些请求中我们需要的元素,对于线上监控以及业务问题定 ...

  2. (高级篇 Netty多协议开发和应用)第十章-Http协议开发应用(基于Netty的HttpServer和HttpClient的简单实现)

    1.HttpServer package nettyHttpTest; import io.netty.bootstrap.ServerBootstrap; import io.netty.chann ...

  3. Netty入门2之----手动搭建HttpServer

    在上一章中我们认识了netty,他有三大优点:并发高,传输快,封装好.在这一章我们来用Netty搭建一个HttpServer,从实际开发中了解netty框架的一些特性和概念. netty.png 认识 ...

  4. Mina、Netty、Twisted一起学(八):HTTP服务器

    HTTP协议应该是目前使用最多的应用层协议了,用浏览器打开一个网站就是使用HTTP协议进行数据传输. HTTP协议也是基于TCP协议,所以也有服务器和客户端.HTTP客户端一般是浏览器,当然还有可能是 ...

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

    Netty的主页:http://netty.io/index.html 使用的Netty的版本:netty-4.0.23.Final.tar.bz2 ‐ 15-Aug-2014 (Stable, Re ...

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

    本章介绍 获得Netty4最新的版本号 设置执行环境,以构建和执行netty程序 创建一个基于Netty的server和client 拦截和处理异常 编制和执行Nettyserver和client 本 ...

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

    一.HTTP协议简介 应用层协议http,发展至今已经是http2.0了,拥有以下特点: (1) CS模式的协议 (2) 简单 - 只需要服务URL,携带必要的请求参数或者消息体 (3) 灵活 - 任 ...

  8. 【netty这点事儿】ByteBuf 的使用模式

    堆缓冲区 最常用的 ByteBuf 模式是将数据存储在 JVM 的堆空间中. 这种模式被称为支撑数组(backing array), 它能在没有使用池化的情况下提供快速的分配和释放. 直接缓冲区 直接 ...

  9. netty的简单的应用例子

    一.简单的聊天室程序 public class ChatClient { public static void main(String[] args) throws InterruptedExcept ...

随机推荐

  1. HDFS基本知识整理

    设计理念:         1.超大文件         2.流式数据访问         3.商用普通硬件 不适合场景:         1.低时间延迟的数据访问         2.大量的小文件 ...

  2. vim中执行shell命令小结

    vim中执行shell命令,有以下几种形式 1):!command 不退出vim,并执行shell命令command,将命令输出显示在vim的命令区域,不会改变当前编辑的文件的内容 例如:!ls -l ...

  3. 使用go语言后的感受

    前两天我说过为了学习go语言去学习了一遍python,当我完成了python的学习后,昨天中午就去学习了go语言.以下简称之为golang. 我用的操作系统是windows xp,golang对xp还 ...

  4. C#更改控制台文本颜色

    C#更改控制台文本的前景色和背景色   关键字:C# NET 控制台 前景色 背景色地址:http://www.cnblogs.com/txw1958/archive/2012/12/07/cshar ...

  5. oracle中操作数据

    使用特定格式插入日期值 insert into emp values (,', to_date('1988-11-11','yyyy-mm-dd'), ); ,); 使用子查询插入数据 create ...

  6. Qt中使用Firebird 和 Firebird Embedded

    编译数据库连接插件 拷贝ibase.h,fbclient_ms.lib(改名gds32_ms.lib)等到ibase.pro项目文件夹下 configure -platform win32-msvc2 ...

  7. 常用的机器学习&数据挖掘知识点【转】

    转自: [基础]常用的机器学习&数据挖掘知识点 Basis(基础): MSE(Mean Square Error 均方误差),LMS(LeastMean Square 最小均方),LSM(Le ...

  8. 修复jquery.treeview的增加子节点的方法的bug

    1.修复理由 在一个android项目中用到了treeview控件(本来自己通过android的原生api实现了一个http://www.cnblogs.com/Mr-Nobody/p/3527688 ...

  9. 【BZOJ】【2693】JZPTAB

    莫比乌斯反演 PoPoQQQ讲义第5题,是BZOJ 2154的升级版(多次询问) 题解:http://blog.csdn.net/popoqqq/article/details/42078725 WA ...

  10. python参考手册--第1章python简介

    1.if __name__ == '__main__': 直接运行myModel.py时,当前模块的名字是main:import myModel然后运行的时候当前模块的名字是myModel. 2.ev ...