Netty构建Http服务器
Netty 是一个基于 JAVA NIO 类库的异步通信框架,它的架构特点是:异步非阻塞、基于事件驱动、高性能、高可靠性和高可定制性。换句话说,Netty是一个NIO框架,使用它可以简单快速地开发网络应用程序,比如客户端和服务端的协议。Netty大大简化了网络程序的开发过程比如TCP和UDP的 Socket的开发。Netty 已逐渐成为 Java NIO 编程的首选框架,Netty中,通讯的双方建立连接后,会把数据按照ByteBuf的方式进行传输,因此我们在构建Http服务器的时候就是通过HttpRequestDecoder对ByteBuf数据流进行处理,转换成http的对象。代码如下:
maven依赖
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.0.Final</version>
</dependency>
HttpServer类
package com.example.demo.netty; import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec; public class HttpServer { public static void main(String[] args) throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new HttpServerHandler());
}
});
ChannelFuture f = b.bind(8080).sync();
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
}
HttpServerHandler类
package com.example.demo.netty; import java.io.UnsupportedEncodingException; import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.QueryStringDecoder; class HttpServerHandler extends ChannelInboundHandlerAdapter { @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws UnsupportedEncodingException { if (msg instanceof HttpRequest) { // 请求,解码器将请求转换成HttpRequest对象
HttpRequest request = (HttpRequest) msg; // 获取请求参数
QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
String name = "netty";
if(queryStringDecoder.parameters().get("name") != null) {
name = queryStringDecoder.parameters().get("name").get(0);
} // 响应HTML
String responseHtml = "<html><body>Hello, " + name + "</body></html>";
byte[] responseBytes = responseHtml.getBytes("UTF-8");
int contentLength = responseBytes.length; // 构造FullHttpResponse对象,FullHttpResponse包含message body
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(responseBytes));
response.headers().set("Content-Type", "text/html; charset=utf-8");
response.headers().set("Content-Length", Integer.toString(contentLength)); ctx.writeAndFlush(response);
}
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
运行HttpServer中main方法,启动httpServer,打开浏览器输入http://localhost:8080?name=zhangsan ,结果如下:
Netty构建Http服务器的更多相关文章
- Netty构建游戏服务器(一)--基本概念与原理
一,Netty是什么 1,Netty是由 JBOSS提供的一个 java开源框架. 2,Netty是JAR包,一般使用ALL-IN-ONE的JAR包就可以开发了. 3,Netty不需要运行在Tomca ...
- Netty构建游戏服务器(三)--netty spring简单整合
一,基本方法 上节实现了netty的基本连接,这节加入spring来管理netty,由spring来开启netty服务. 在netty服务器中,我们建立了三个类:HelloServer(程序主入口) ...
- Netty构建游戏服务器(二)--Hello World
一,准备工作 1,netty-all-4.1.5.Final.jar(官网下载) 2,eclipse 二,步骤概要 1,服务器开发 (1),创建Server类 该类是程序的主入口,有main方法,服务 ...
- 基于Netty打造RPC服务器设计经验谈
自从在园子里,发表了两篇如何基于Netty构建RPC服务器的文章:谈谈如何使用Netty开发实现高性能的RPC服务器.Netty实现高性能RPC服务器优化篇之消息序列化 之后,收到了很多同行.园友们热 ...
- Netty构建分布式消息队列(AvatarMQ)设计指南之架构篇
目前业界流行的分布式消息队列系统(或者可以叫做消息中间件)种类繁多,比如,基于Erlang的RabbitMQ.基于Java的ActiveMQ/Apache Kafka.基于C/C++的ZeroMQ等等 ...
- Netty构建分布式消息队列实现原理浅析
在本人的上一篇博客文章:Netty构建分布式消息队列(AvatarMQ)设计指南之架构篇 中,重点向大家介绍了AvatarMQ主要构成模块以及目前存在的优缺点.最后以一个生产者.消费者传递消息的例子, ...
- 教你如何构建异步服务器和客户端的 Kotlin 框架 Ktor
Ktor 是一个使用 Kotlin 以最小的成本快速创建 Web 应用程序的框架. Ktor 是一个用于在连接系统(connected systems)中构建异步服务器和客户端的 Kotlin 框架. ...
- 客户端(springmvc)调用netty构建的nio服务端,获得响应后返回页面(同步响应)
后面考虑通过netty做一个真正意义的简约版RPC框架,今天先尝试通过正常调用逻辑调用netty构建的nio服务端并同步获得返回信息.为后面做铺垫 服务端实现 我们先完成服务端的逻辑,逻辑很简单,把客 ...
- NodeJs+http+fs+request+cheerio 采集,保存数据,并在网页上展示(构建web服务器)
目的: 数据采集 写入本地文件备份 构建web服务器 将文件读取到网页中进行展示 目录结构: package.json文件中的内容与上一篇一样:NodeJs+Request+Cheerio 采集数据 ...
随机推荐
- vc和halcon数据的相互赋值
// HTuple→VC 数据类型转换 HTuple hTuple = 1234; int i = hTuple[0].I(); // i=1234 long l = hTuple[0].L(); / ...
- Lazy<T> 提供对延迟初始化的支持
延迟初始化 就是在第一次使用的时候在 进行类的初始化 public class Student { public Student() { this.Name = "DefaultName& ...
- Replication--Alwayson+复制发布
场景:主服务器:RepServer1从服务器:RepServer2监听者:RepListener分发库:DisServer发布数据库:RepDB1配置:1>设置DisServer为分发服务器,在 ...
- C#中匿名函数、委托delegate和Action、Func、Expression、还有Lambda的关系和区别
以前一直迷迷糊糊的,现在总算搞明白. Lambda表达式 Lamda表达式基本写法是()=>{ };Lambda和方法一样都可以传入参数和拥有返回值.(int x)=>{return x; ...
- Unit Vector Compression
Recently, I compared a few methods for compressing generic unit vectors. The method used in Cry Engi ...
- 「AH2017/HNOI2017」礼物
题目链接 戳我 \(Solution\) 应为我们可以将任意一个数列加上一个非负整数,即可以变为将一个数列加上一个整数(可以为负),我们将这个整数设为\(z\).所以要求的式子的变为: \[\sum_ ...
- D. Magic Box(几何)
One day Vasya was going home when he saw a box lying on the road. The box can be represented as a re ...
- 一分钟了解 TCP/IP 模型
原文讲的不是特别细,为了便于理解,我颠倒了顺序. 写在开始 我们需要知道协议到底是什么. 在网络上,一个协议对应于管理系统之间如何相互通信的规则. 然后我们需要知道什么是协议族. 一个协议族是一系列协 ...
- freemarker模板跟java代码放在一起
在配置 freemarkerConfig时加上 <property name="templateLoaderPath" value="classpath:hello ...
- JavaWeb学习笔记(二十二)—— 过滤器filter
一.什么是过滤器 过滤器filter是JavaWeb三大组件之一,它与Servlet很相似!不过过滤器是用来拦截请求的,而不是处理请求的.WEB开发人员通过Filter技术,对web服务器管理的所有w ...