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 ...
随机推荐
- Oracle RAC中的一台机器重启以后无法接入集群
前天有个同事说有套AIX RAC的其中一台服务器重启了操作系统以后,集群资源CSSD的资源一直都在START的状态,检查日志输出有如下内容: [ CSSD][1286]clssnmv ...
- iOS/Objective-C开发 字典NSDictionary的深复制(使用category)
目标:把NSDictionary对象转换成NSMutableDictionary对象,对象内容是字符串数组,需要实现完全复制(深复制). 如果调用NSDictionary的mutableCopy方法, ...
- [原]项目进阶 之 持续构建环境搭建(三)Maven环境搭建
上次的博文项目进阶 之 持续构建环境搭建(二)Nexus私服器中,我们搭建了一个Nexus的maven私服,这次我们来重点讲解一下Maven的安装和配置.这里说明一下这次的环境搭建,比较基础,但却非常 ...
- java 产生随机数的方法
有三种方法: Math.random():这个方法返回一个[0.0, 1.0)的一个随机double型数.它实际是调用Random类的nextDouble()方法.只不过Math类使用的是一个静态随机 ...
- Cocos2D-x搭建新环境注意事项
网上资源都说安装Python后, 设置环境变量, 解压Cocos2Dx压缩包就OK, 但运行CppTest还是会报错, 以下是错误解决方案: 1. 错误提示 error LNK1123: failur ...
- 【BZOJ】【3158】千钧一发
网络流/最小割 这题跟BZOJ 3275限制条件是一样的= =所以可以用相同的方法去做……只要把边的容量从a[i]改成b[i]就行了- (果然不加当前弧优化要略快一点) /************** ...
- [CF]codeforces round#366(div2)滚粗记
开场心理活动:啊打完这场大概有1700了吧 中途心理活动:啊这个ABC看起来都随便做啊 死亡原因:欸怎么没网了 -75 .. A [题意]Hulk说完一句I hate会说that I love 然后是 ...
- cf 363D
贪心加二分 虽然比赛后才过 ........ /************************************************************************* &g ...
- HTTP长轮询和短轮询
http 协议介绍: http 协议是请求/响应范式的, 每一个 http 响应都是由一个对应的 http 请求产生的; http 协议是无状态的, 多个 http 请求之间是没有关系的. http ...
- zoj 3232 It's not Floyd Algorithm(强联通分量,缩点)
题目 /******************************************************************/ 以下题解来自互联网:Juny的博客 思路核心:给你的闭包 ...