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 ...
随机推荐
- 2018ACM/ICPC 焦作网络预选赛-A Magic Mirror
Jessie has a magic mirror. Every morning she will ask the mirror: 'Mirror mirror tell me, who is the ...
- bash单引号嵌套
转自:https://blog.jysoftware.com/2015/12/bash-%E6%80%8E%E4%B9%88%E5%81%9A%E5%8D%95%E5%BC%95%E5%8F%B7%E ...
- Day 09 作业
简述定义函数的三种方式 有参函数, 无参函数, 空函数 简述函数的返回值 函数内部代码经过一系列的逻辑处理返回的结果 简述函数的参数 函数的参数分形参和实参 形参: 定义函数阶段, 括号内定义的参数, ...
- 【Nodejs】375- 如何加快 Node.js 应用的启动速度
我们平时在开发部署 Node.js 应用的过程中,对于应用进程启动的耗时很少有人会关注,大多数的应用 5 分钟左右就可以启动完成,这个过程中会涉及到和集团很多系统的交互,这个耗时看起来也没有什么问题. ...
- 【Eureka】集群搭建
[Eureka]集群搭建 转载============================================== ====================================== ...
- NodeJS3-2基础API----Buffer(缓冲器)
Buffer(缓冲器) Buffer是用于处理二进制数据流的 实例类似整数数组,大小固定(实例化之后,是多大就多大,不能进行变更) C++代码在V8 对外分配物理内存 Buffer是全局变量,没必要使 ...
- 小白的springboot之路(十二)、集成log4j2日志
0.前言 日志记录对系统来说必不可少,spring boot中常用的日志组件有log4j.logback.log4j2,其中logback是spring boot默认的,已自带:选用log4j2就可以 ...
- conda docker镜像
之前的python环境,使用ubuntu安装pip来安装python依赖,但是遇到缺少某些库的版本,比如一个项目需要用到faiss,pip只有最新的1.5.3版本,但是这个版本使用了较新的CPU指令, ...
- python操作文件和目录查看、创建、删除、复制
python内置了os模块可以直接调用操作系统提供的接口函数,os.name查询的是操作系统,‘nt’表示windows系统 >>> import os >>> o ...
- tp5.1批量删除商品
选中要删除的商品,点击批量删除 先在控制器使用sql语句查出商品信息goods 然后在html源码中使用goods变量. <table> {foreach $goods as $item} ...