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. 斐波那契(Fibonacci)数列的七种实现方法

    废话不多说,直接上代码 #include "stdio.h" #include "queue" #include "math.h" usin ...

  2. 安装Golang 1.6及开发环境

    安装Golang 1.6及开发环境=====================================> 下载软件    * go1.4.2.linux-amd64.tar.gz     ...

  3. c# this.location和e.X的区别

    this.location是窗口当前位置 e.X是具体事件的相对坐标 size是窗口尺寸宽和高

  4. 关于sql语句in的使用注意规则

    想必大家都用过sql中的in语句吧,我这里描述下我遇到的一种in语句问题,并总结一些给大家分享下,不对的地方还希望大虾指点下. 问题描述:IN子查询时,子查询中字段在表中不存在时语句却不报错 平常工作 ...

  5. iTween基础之Rotate(旋转角度)

    一.基础介绍:二.基础属性 原文地址 :http://blog.csdn.net/dingkun520wy/article/details/50696489 一.基础介绍 RotateTo:旋转游戏物 ...

  6. C++(MFC)

    C++(MFC) 1.关联变量(与控件关联): (1)一组单选按钮:需要将第一个单选按钮的Group选项设为true,则单选按钮就为一组(组框为标示作用).选中第一个则为0,第二个为1,依次类推(P2 ...

  7. Ffmpeg 定位文件(seek file)

    有朋友问到ffmpeg播放文件如何定位问题,我想到应该还有一些新手朋友对这一块比较陌生.ffmpeg定位问题用到seek方法,代码 如下: void SeekFrame(AVFormatContext ...

  8. 原型prototype -- 深入理解javascript

    /* 原型Prototype */ //一.原型 //原型使用一 var calculator = function (dlg, tax) { this.dlg = dlg; this.tax = t ...

  9. mvc异步表单遇到的问题

    1,mvc异步表单遇到的问题    问题:使用jqury easy ui 时提交异步数据不能请求到服务器   解决办法:经过细心调试和检测,发现jqury的加载顺序放在了easy ui之后,所以首先加 ...

  10. html+css学习笔记 3[浮动]

    inline-block/float(浮动) 回顾:inline-block 特性:      1.块在一排显示 2.内联支持宽高 3.默认内容撑开宽度 4.标签之间的换行间隙被解析(问题) 5.ie ...