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. 安装percona-toolkit提示的报错

    [root@hank-yoon export]# tar -xvf percona-toolkit_2.2.15-2.tar.gz [root@hank-yoon export]# cd percon ...

  2. 【nodejs】关于 alert 和 document

    Microsoft Windows [版本 6.1.7601] 版权所有 (c) 2009 Microsoft Corporation.保留所有权利. C:\Windows\system32>n ...

  3. Flash制作遇到的小问题1--为何变形需要将图形打散(Ctrl+b)

    今天上Flash实验课遇到一个小问题,就是我在画一个矩形如下图:

  4. mysql_fetch_row()与mysql_fetch_array()的使用介绍

    mysql_fetch_array --从结果集中取得一行作为关联数组,或数字数组,或二者兼有 说明array mysql_fetch_array ( resource result [, int r ...

  5. 20145120 《Java程序设计》第4周学习总结

    20145120 <Java程序设计>第4周学习总结 教材学习内容总结 -定义子类,加"extends+父类名"以继承父类. -子类只能继承一个父类 -编辑器会检查等号 ...

  6. MITK Tutorial (三)

    Step 2: Use the template with the plugins to read a image 在exampleplugin插件中QmitkAwesomeView.cpp中添加头文 ...

  7. EntityFramework Add方法与Attach区别

    一 先发问. 问题:在使用EF过程中,能否有一个方法可以直接执行传入的SQL语句.纠结的只找到了调用存储过程的方法,难道要SqlHelper.cs?    二 友情提示 本文内容参考自MSDN. 三 ...

  8. BZOJ 2763: [JLOI2011]飞行路线 spfa dp

    题目链接: http://www.lydsy.com/JudgeOnline/problem.php?id=2763 题解: d[x][kk]表示从s到x用了kk次免费机会的最少花费. 代码: #in ...

  9. MVC3+AutoFac实现程序集级别的依赖注入

    1.介绍      所谓程序集级别的依赖注入是指接口和实现的依赖不使用配置文件或硬代码实现(builder.RegisterType<UserInfoService>().As<IU ...

  10. c++ 虚继承

    虚继承(个人感觉用到的地方不多,项目中没有用到这个的) 最典型的例子就是iostream的继承方式 class istream : virtual public ios{...};//此处就是虚继承, ...