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 ...
随机推荐
- hoverdir
js 引入 jq && modernizr.custom.97074.js &&jquery.hoverdir.js css 引入style.css html代 ...
- git配置文件—— .gitattributes
目录 .gitattributes 文档 1. gitattributes文件以行为单位设置一个路径下所有文件的属性,格式如下: 2. 在gitattributes文件的一行中,一个属性(以text属 ...
- 使用 Spring 提供的 restTemplate 完成 Http 服务消费
RestTemplate 介绍 RestTemplate 是 Spring 提供的用于访问 Rest 服务的客户端,RestTemplate 提供了多种便捷访问远程 Http 服务的方法,能够大大提高 ...
- String and Arrays
Description 有一个N*N的字符矩阵,从上到下依次记为第1行,第2行,--,第N行,从左至右依次记为第1列,第2列,--,第N列. 对于这个矩阵会进行一系列操作,但这些操作只有两类: ...
- ARTS-S linux查看进程打开的文件数
当怀疑进程打开文件没有关闭时,可以反复执行以下命令,查看进程打开的文件数是否会不断增加. ls -l /proc/18707/fd | wc -l 其中18707是进程id
- html小工具——文章注释编辑器
在网上阅读文章时,读者时常会想针对某段文字写一些自己的感想,可惜大部分阅读网站并不提供这样的功能,读者往往只能将文本复制到本地或在线的编辑器中编辑注释,之后如果想在其他地方回顾这些注释也必须先本地安装 ...
- [权限管理系统(四)]-spring boot +spring security短信认证+redis整合
[权限管理系统]spring boot +spring security短信认证+redis整合 现在主流的登录方式主要有 3 种:账号密码登录.短信验证码登录和第三方授权登录,前面一节Sprin ...
- zabbix漏洞
1:Zabbix配置不当安全事件 ①案例事件 sohu的zabbix,可导致内网渗透 http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2015-0 ...
- oracle 日常巡检
1. 检查数据库基本状况 包含:检查Oracle实例状态,检查Oracle服务进程,检查Oracle监听进程,共三个部分. 1.1. 检查Oracle实例状态 select instance_name ...
- 3个Spring Boot核心注解,你知道几个?
Spring Boot 核心注解讲解 Spring Boot 最大的特点是无需 XML 配置文件,能自动扫描包路径装载并注入对象,并能做到根据 classpath 下的 jar 包自动配置. 所以 S ...