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 ...
随机推荐
- springboot+mybatis sql 打印在控制台
第一种方法 在mybatis文件夹下新建mybatis-config.xml <?xml version="1.0" encoding="UTF-8" ? ...
- (重点)Python深入之Python内存管理机制你会吗?
前言本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理.作者:醍醐三叶 请注意:如果你平时学Python遇到问题找不到人解答?或者没有 ...
- 上手spring boot项目(三)之spring boot整合mybatis进行增删改查
使用mybatis框架进行增删改查大致有两种基础方式,一种扩展方式.两种基础方式分别是使用xml映射文件和使用方法注解.扩展方式是使用mybatis-plus的方式,其用法类似于spring-data ...
- CentOS 8安装
1.VMware workstation14Pro安装 下载蓝点网,序列号也有,直接输入,永久激活 2.CentOS8下载 CentOS8下载地址:清华源 3.CentOS8安装
- 【JS】403- JavaScript 工具函数大全(新)
前言 一线大厂笔试题灵感来源 目录: 第一部分:数组 第二部分:函数 第三部分:字符串 第四部分:对象 第五部分:数字 第六部分:浏览器操作及其它 筛选自以下两篇文章: <127 Helpful ...
- 【CentOS7】设置静态IP地址
[CentOS7]设置静态IP地址 转载:https://www.cnblogs.com/yangchongxing/p/10645871.html 图像化修改 nmtui 查看当前网卡名称 # if ...
- javascript的ES6学习总结(第三部分)
1.ES6中的面向对象的类 1.1.定义类 在ES5中,我们写一个类,通常是这么写的 function Person(name,age){ this.name = name; this.age = a ...
- Linux服务器部署.Net Core笔记:三、CentOS 7上安装.NetCore运行环境
1.要开始安装 .NET,您需要注册 Microsoft 签名密钥并添加 Microsoft 产品提要.每台机器只需要做一次. 打开命令提示符并运行以下命令:sudo rpm -Uvh https:/ ...
- 服务发现(consul)搭建
服务发现(consul)搭建 下载最新版 consul 本人使用的版本为1.5.1,操作系统:window server 2008 consul部署的时候分为客户端和服务端,本次操作服务器2台,客户端 ...
- 在Join中使用FIND_IN_SET
$d['a.cold'] = 2; $d['b.PostId'] = $up_id['PostId']; $d['b.F_Id'] = $up_id['Id']; $d['WorkinTime'] = ...