用netty来启动一个简单的可处理http请求的服务器。

依照前面写的使用netty的过程。贴上代码

server

 import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel; /**
* @ClassName: TestServe
* @Description: 描述 主要作用是写一个可以支持 http 请求的伪服务器。可以看到请求的头和数据 ,也可以自己构建response
* @CreateDate: 2019/7/3 23:08
* @Version: 1.0
*/
public class TestServer { public static void main(String[] args) throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup();//线程,用来接收 事件循环组 死循环
EventLoopGroup workerGroup = new NioEventLoopGroup();//线程,用来处理 事件循环组 死循环 try{
//启动器
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup)//添加设置两个线程组
.channel(NioServerSocketChannel.class)
.childHandler(new TestSereverInitlalizer());//这里去设置初始化类 ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();//阻塞,等待 channelFuture.channel().closeFuture().sync();
}finally {
bossGroup.shutdownGracefully();//优雅关闭
workerGroup.shutdownGracefully();
} }
}

Initlalizer

 import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpServerCodec; public class TestSereverInitlalizer extends ChannelInitializer<SocketChannel> { @Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("httpServerCodec",new HttpServerCodec());//http里用的
pipeline.addLast("testHttpSereverHandle", new TestHttpServerHandler());//把前面设置的handler加到最后 }
}

Handler

 import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil; import java.net.URI;
import java.net.URL; public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> { @Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { System.out.println(msg.getClass()); System.out.println(ctx.channel().remoteAddress()); if(msg instanceof HttpRequest) {//如果没加这个,用curl访问时,会报错,用浏览器访问不会报错
// System.out.println("执行了!!!!!"); HttpRequest httpRequest = (HttpRequest) msg; System.out.println("请求方法名" + httpRequest.getMethod().name()); URI uri = new URI(httpRequest.uri());
if("/favicon.ico".equals(uri.getPath())) {
System.out.println("请求 favicon.ico");
return;
} //向客户端返回的内容
ByteBuf content = Unpooled.copiedBuffer("Hello world", CharsetUtil.UTF_8);
//构建response
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK,content);
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes()); ctx.writeAndFlush(response);
ctx.channel().close();
} } @Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("channel active");
super.channelActive(ctx);
} @Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("channel inactive");
super.channelInactive(ctx);
} @Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
System.out.println("channel registered");
super.channelRegistered(ctx);
} @Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
System.out.println("channel unregistered");
super.channelUnregistered(ctx);
} @Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
System.out.println("handler added");
super.handlerAdded(ctx);
}
}

2、netty第一个例子,简单的http服务器的更多相关文章

  1. 《深度解析Tomcat》 第一章 一个简单的Web服务器

    本章介绍Java Web服务器是如何运行的.从中可以知道Tomcat是如何工作的. 基于Java的Web服务器会使用java.net.Socket类和java.net.ServerSocket类这两个 ...

  2. Tomcat剖析(一):一个简单的Web服务器

    Tomcat剖析(一):一个简单的Web服务器 1. Tomcat剖析(一):一个简单的Web服务器 2. Tomcat剖析(二):一个简单的Servlet服务器 3. Tomcat剖析(三):连接器 ...

  3. ElasticSearch 5学习(5)——第一个例子(很实用)

    想要知道ElasticSearch是如何使用的,最快的方式就是通过一个简单的例子,第一个例子将会包括基本概念如索引.搜索.和聚合等,需求是关于公司管理员工的一些业务. 员工文档索引 业务首先需要存储员 ...

  4. emberjs学习一(环境和第一个例子)

    code { margin: 0; padding: 0; white-space: pre; border: none; background: transparent; } code, pre t ...

  5. Qt之QCustomPlot绘图(一)配置和第一个例子

    最近一个用Qt开发的项目需要绘制坐标曲线,我在老师的指点下使用了QCustomPlot这个插件,使用方法简单,功能还算不错. 可是在网上找了很多资料和博文都只是将官方提供的例子演示一遍,没有系统全面的 ...

  6. 键盘过滤第一个例子ctrl2cap(4.1~4.4)汇总,测试

    键盘过滤第一个例子ctrl2cap(4.1~4.4)汇总,测试 完整源代码 /// /// @file ctrl2cap.c /// @author wowocock /// @date 2009-1 ...

  7. springmvc的介绍和第一个例子

    SpringMVC是Spring 框架自带的一部分. SpringMVC底层基于:Servlet Struts2底层基于:filter struts1底层基于:Servlet spring 各模块 我 ...

  8. 04springMVC结构,mvc模式,spring-mvc流程,spring-mvc的第一个例子,三种handlerMapping,几种控制器,springmvc基于注解的开发,文件上传,拦截器,s

     1. Spring-mvc介绍 1.1市面上流行的框架 Struts2(比较多) Springmvc(比较多而且属于上升的趋势) Struts1(即将被淘汰) 其他 1.2  spring-mv ...

  9. [转]ZooKeeper学习第一期---Zookeeper简单介绍

    ZooKeeper学习第一期---Zookeeper简单介绍 http://www.cnblogs.com/sunddenly/p/4033574.html 一.分布式协调技术 在给大家介绍ZooKe ...

随机推荐

  1. KubeSphere 日志备份与恢复实践

    为什么需要日志备份 KubeSphere 日志系统使用 Fluent Bit + ElasticSearch 的日志采集存储方案,并通过 Curator 实现对 Index 的生命周期管理,定期清理久 ...

  2. JWT攻击手册:如何入侵你的Token

    JSON Web Token(JWT)对于渗透测试人员而言,可能是一个非常吸引人的攻击途径.因为它不仅可以让你伪造任意用户获得无限的访问权限,而且还可能进一步发现更多的安全漏洞,如信息泄露,越权访问, ...

  3. Bomb后端云使用

    Bomb是后台云托管工具,在Bomb官网注册会员,即可免费使用后台数据库服务.https://www.bmob.cn/app/list 创建应用后,在设置里获取密钥.根据官方文档集成. 在集成后运行时 ...

  4. HDU4670 cube number on a tree(点分治+三进制加法)

    The country Tom living in is famous for traveling. Every year, many tourists from all over the world ...

  5. Python3 并发编程3

    目录 GIL全局解释器锁 基本概念 多线程的作用 死锁现象 递归锁 信号量 线程队列 GIL全局解释器锁 基本概念 global interpreter lock 全局解释器锁 GIL不是Python ...

  6. Day 09 作业

    简述定义函数的三种方式 有参函数, 无参函数, 空函数 简述函数的返回值 函数内部代码经过一系列的逻辑处理返回的结果 简述函数的参数 函数的参数分形参和实参 形参: 定义函数阶段, 括号内定义的参数, ...

  7. 【hibernate】常用注解

    [hibernate]常用注解 转载:https://www.cnblogs.com/yangchongxing/p/10357118.html 目录 ======================== ...

  8. Django模型层—ORM

    目录 一.模型层(models) 1-1. 常用的字段类型 1-2. 字段参数 1-3. 自定义char字段 1-4. 外键关系 二.Django中测试脚本的使用 三.单表操作 3-1. 添加记录 3 ...

  9. Java8 Stream —— 更丝滑的集合操作方式

    一.概念 Stream是一种可供流式操作的数据视图有些类似数据库中视图的概念它不改变源数据集合如果对其进行改变的操作它会返回一个新的数据集合. 总的来讲它有三大特性:在之后我们会对照着详细说明     ...

  10. 图文结合深入理解JS中的this值

    文章目录 Js 中奇妙的this值 1. 初探this 2. this指向总结 2.1 普通函数调用 2.2 对象的方法调用 2.3 构造函数调用 2.4 利用call,apply,bind方法调用函 ...