netty httpserver
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的更多相关文章
- SpringCloud升级之路2020.0.x版-42.SpringCloudGateway 现有的可供分析的请求日志以及缺陷
本系列代码地址:https://github.com/JoJoTec/spring-cloud-parent 网关由于是所有外部用户请求的入口,记录这些请求中我们需要的元素,对于线上监控以及业务问题定 ...
- (高级篇 Netty多协议开发和应用)第十章-Http协议开发应用(基于Netty的HttpServer和HttpClient的简单实现)
1.HttpServer package nettyHttpTest; import io.netty.bootstrap.ServerBootstrap; import io.netty.chann ...
- Netty入门2之----手动搭建HttpServer
在上一章中我们认识了netty,他有三大优点:并发高,传输快,封装好.在这一章我们来用Netty搭建一个HttpServer,从实际开发中了解netty框架的一些特性和概念. netty.png 认识 ...
- Mina、Netty、Twisted一起学(八):HTTP服务器
HTTP协议应该是目前使用最多的应用层协议了,用浏览器打开一个网站就是使用HTTP协议进行数据传输. HTTP协议也是基于TCP协议,所以也有服务器和客户端.HTTP客户端一般是浏览器,当然还有可能是 ...
- 基于Netty4的HttpServer和HttpClient的简单实现
Netty的主页:http://netty.io/index.html 使用的Netty的版本:netty-4.0.23.Final.tar.bz2 ‐ 15-Aug-2014 (Stable, Re ...
- Netty In Action中国版 - 第二章:第一Netty程序
本章介绍 获得Netty4最新的版本号 设置执行环境,以构建和执行netty程序 创建一个基于Netty的server和client 拦截和处理异常 编制和执行Nettyserver和client 本 ...
- netty高级篇(3)-HTTP协议开发
一.HTTP协议简介 应用层协议http,发展至今已经是http2.0了,拥有以下特点: (1) CS模式的协议 (2) 简单 - 只需要服务URL,携带必要的请求参数或者消息体 (3) 灵活 - 任 ...
- 【netty这点事儿】ByteBuf 的使用模式
堆缓冲区 最常用的 ByteBuf 模式是将数据存储在 JVM 的堆空间中. 这种模式被称为支撑数组(backing array), 它能在没有使用池化的情况下提供快速的分配和释放. 直接缓冲区 直接 ...
- netty的简单的应用例子
一.简单的聊天室程序 public class ChatClient { public static void main(String[] args) throws InterruptedExcept ...
随机推荐
- andriod ADB命令的使用
android ADB命令的使用 ADB是一个 客户端-服务器端 程序, 其中客户端是你用来操作的电脑, 服务器端是android设备. 先说安装方法, 电脑上需要安装客户端. 客户端包含在sdk里. ...
- windows下设置socket的connect超时
SOCKET Open(const char* strIP, UINT nPort, int nTimeOut) { SOCKET sockfd = NULL; ...
- php开发过程中用什么方法来加快页面的加载速度
1,数据库优化;2,php缓存;3,使用zend引擎(其它框架);4,分布式部署;5,静态
- Css compatibility
http://meiert.com/en/indices/css-properties/ http://www.standardista.com/css3/css3-selector-browser- ...
- Windows程序消息机制浅析
1.消息 消息是由MSG结构体来表示的.如下: typedef struct tagMSG { HWND hwnd; UINT message; WPARAM wParam; LPARAM lPar ...
- 机器学习(Machine Learning)&深度学习(Deep Learning)资料【转】
转自:机器学习(Machine Learning)&深度学习(Deep Learning)资料 <Brief History of Machine Learning> 介绍:这是一 ...
- C# ASP.NET系统缓存全解析
原文:http://blog.csdn.net/wyxhd2008/article/details/8076105 目录(?)[-] 系统缓存的概述 页面输出缓存 页面局部缓存 文件缓存依赖 数据库缓 ...
- OpenCV之mixChannels()函数使用说明
step 1: 函数功能说明 mixChannels主要就是把输入的矩阵(或矩阵数组)的某些通道拆分复制给对应的输出矩阵(或矩阵数组)的某些通道中,其中的对应关系就由fromTo参数制定. step ...
- JSON-JObject
http://james.newtonking.com/json/help/index.html http://www.cnblogs.com/usharei/archive/2012/04/24/2 ...
- hibernate4.0中SessionFactory的创建
创建SessionFactory 首先创建Configuration对象,主要方式是: new Configuration().configure() 默认情况下Hibernate会去classPat ...