2、netty第一个例子,简单的http服务器
用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服务器的更多相关文章
- 《深度解析Tomcat》 第一章 一个简单的Web服务器
本章介绍Java Web服务器是如何运行的.从中可以知道Tomcat是如何工作的. 基于Java的Web服务器会使用java.net.Socket类和java.net.ServerSocket类这两个 ...
- Tomcat剖析(一):一个简单的Web服务器
Tomcat剖析(一):一个简单的Web服务器 1. Tomcat剖析(一):一个简单的Web服务器 2. Tomcat剖析(二):一个简单的Servlet服务器 3. Tomcat剖析(三):连接器 ...
- ElasticSearch 5学习(5)——第一个例子(很实用)
想要知道ElasticSearch是如何使用的,最快的方式就是通过一个简单的例子,第一个例子将会包括基本概念如索引.搜索.和聚合等,需求是关于公司管理员工的一些业务. 员工文档索引 业务首先需要存储员 ...
- emberjs学习一(环境和第一个例子)
code { margin: 0; padding: 0; white-space: pre; border: none; background: transparent; } code, pre t ...
- Qt之QCustomPlot绘图(一)配置和第一个例子
最近一个用Qt开发的项目需要绘制坐标曲线,我在老师的指点下使用了QCustomPlot这个插件,使用方法简单,功能还算不错. 可是在网上找了很多资料和博文都只是将官方提供的例子演示一遍,没有系统全面的 ...
- 键盘过滤第一个例子ctrl2cap(4.1~4.4)汇总,测试
键盘过滤第一个例子ctrl2cap(4.1~4.4)汇总,测试 完整源代码 /// /// @file ctrl2cap.c /// @author wowocock /// @date 2009-1 ...
- springmvc的介绍和第一个例子
SpringMVC是Spring 框架自带的一部分. SpringMVC底层基于:Servlet Struts2底层基于:filter struts1底层基于:Servlet spring 各模块 我 ...
- 04springMVC结构,mvc模式,spring-mvc流程,spring-mvc的第一个例子,三种handlerMapping,几种控制器,springmvc基于注解的开发,文件上传,拦截器,s
1. Spring-mvc介绍 1.1市面上流行的框架 Struts2(比较多) Springmvc(比较多而且属于上升的趋势) Struts1(即将被淘汰) 其他 1.2 spring-mv ...
- [转]ZooKeeper学习第一期---Zookeeper简单介绍
ZooKeeper学习第一期---Zookeeper简单介绍 http://www.cnblogs.com/sunddenly/p/4033574.html 一.分布式协调技术 在给大家介绍ZooKe ...
随机推荐
- 压缩感知重构算法之CoSaMP算法python实现
压缩感知重构算法之OMP算法python实现 压缩感知重构算法之CoSaMP算法python实现 压缩感知重构算法之SP算法python实现 压缩感知重构算法之IHT算法python实现 压缩感知重构 ...
- BZOJ 3107 [cqoi2013]二进制a+b (DP)
3107: [cqoi2013]二进制a+b Time Limit: 10 Sec Memory Limit: 128 MBSubmit: 995 Solved: 444[Submit][Stat ...
- Grafana基础
一.Grafana基础 Grafana是一个开源的指标量监测和可视化工具.官方网站为:https://grafana.com/, 常用于展示基础设施的时序数据和应用程序运行分析.Grafana的das ...
- Nginx的事件循环
首先事件循环的起点就是监听端口获取连接,我们可以在ngx_event_core_module模块的ngx_event_process_init函数中看到如下的代码: /* for each liste ...
- 如何妙用Spring 数据绑定机制?
前言 在剖析完 「Spring Boot 统一数据格式是怎么实现的? 」文章之后,一直觉得有必要说明一下 Spring's Data Binding Mechanism 「Spring 数据绑定机制」 ...
- 通过Redis 实现分布式锁_利用Jedis 客户端
前言 分布式锁一般有三种实现方式: 数据库乐观锁:2. 基于Redis的分布式锁:3. 基于ZooKeeper的分布式锁. 本篇博客将介绍第二种方式,基于Redis实现分布式锁. 虽然网上已经有各种介 ...
- gitbook 入门教程之网站域名备案 icp 插件
欢迎访问 gitbook-plugin-icp 官网
- 初学Swoole:PHP7安装Swoole的步骤
本篇文章给大家带来的内容是关于初学Swoole:PHP7安装Swoole的步骤,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助. 环境 这里不在使用apache做为web server. ...
- [NOIP模拟]文本编辑器 题解
bsoj5089 文本编辑器 /* 题意描述 九发明了一个完美的文本编辑器.这个编辑器拥有两个光标(cursor),所以九能够同时在两处地方插入和删除文本.这个编辑器除了正常的编辑功能以外,还有一些只 ...
- 使用node+express+mongodb实现用户注册、登录和验证功能
无论是手机端还是pc端,几乎都包含登录注册方面功能,今天就使用node+express+mongodb实现一套登录注册功能,这里需要自己去安装MongoDB环境,如果没有安装可以看这篇关于MongoD ...