Netty实现简易http_server
Netty可以通过一些handler实现简单的http服务器。具体有三个类,分别是HttpServer.java、ServerHandlerInit.java、BusiHandler.java。
具体代码如下:
HttpServer.java
package cn.enjoyedu.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;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate; /**
* @author Mark老师 享学课堂 https://enjoy.ke.qq.com
* 往期课程和VIP课程咨询 依娜老师 QQ:2133576719
* 类说明:
*/
public class HttpServer {
public static final int port = 6789; //设置服务端端口
private static EventLoopGroup group = new NioEventLoopGroup();
private static ServerBootstrap b = new ServerBootstrap();
private static final boolean SSL = true; public static void main(String[] args) throws Exception {
final SslContext sslCtx;
if (SSL) {
//netty为我们提供的ssl加密,缺省
SelfSignedCertificate ssc = new SelfSignedCertificate();
sslCtx = SslContextBuilder.forServer(ssc.certificate(),
ssc.privateKey()).build();
} else {
sslCtx = null;
}
try {
b.group(group);
b.channel(NioServerSocketChannel.class);
b.childHandler(new ServerHandlerInit(sslCtx));
// 服务器绑定端口监听
ChannelFuture f = b.bind(port).sync();
System.out.println("服务端启动成功,端口是:"+port);
// 监听服务器关闭监听
f.channel().closeFuture().sync();
} finally {
group.shutdownGracefully();
}
}
}
ServerHandlerInit.java
package cn.enjoyedu.server; import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpContentCompressor;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.ssl.SslContext; /**
* @author Mark老师 享学课堂 https://enjoy.ke.qq.com
* 往期课程和VIP课程咨询 依娜老师 QQ:2133576719
* 类说明:
*/
public class ServerHandlerInit extends ChannelInitializer<SocketChannel> { private final SslContext sslCtx; public ServerHandlerInit(SslContext sslCtx) {
this.sslCtx = sslCtx;
} @Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline ph = ch.pipeline();
if (sslCtx != null) {
ph.addLast(sslCtx.newHandler(ch.alloc()));
}
//http响应编码
ph.addLast("encode",new HttpResponseEncoder());
//http请求编码
ph.addLast("decode",new HttpRequestDecoder());
//聚合http请求
ph.addLast("aggre",
new HttpObjectAggregator(10*1024*1024));
//启用http压缩
ph.addLast("compressor",new HttpContentCompressor());
//自己的业务处理
ph.addLast("busi",new BusiHandler()); }
}
BusiHandler.java
package cn.enjoyedu.server; import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil; /**
* @author Mark老师 享学课堂 https://enjoy.ke.qq.com
* 往期课程和VIP课程咨询 依娜老师 QQ:2133576719
* 类说明:
*/
public class BusiHandler extends ChannelInboundHandlerAdapter {
private String result=""; private void send(String content, ChannelHandlerContext ctx,
HttpResponseStatus status){
FullHttpResponse response =
new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,status,
Unpooled.copiedBuffer(content,CharsetUtil.UTF_8));
response.headers().set(HttpHeaderNames.CONTENT_TYPE,
"text/plain;charset=UTF-8");
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } /*
* 收到消息时,返回信息
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
String result="";
//接收到完成的http请求
FullHttpRequest httpRequest = (FullHttpRequest)msg; try{
String path = httpRequest.uri();
String body = httpRequest.content().toString(CharsetUtil.UTF_8);
HttpMethod method = httpRequest.method();
if(!"/test".equalsIgnoreCase(path)){
result = "非法请求:"+path;
send(result,ctx,HttpResponseStatus.BAD_REQUEST);
return;
} //处理http GET请求
if(HttpMethod.GET.equals(method)){
System.out.println("body:"+body);
result="Get request,Response="+RespConstant.getNews();
send(result,ctx,HttpResponseStatus.OK);
} //处理http POST请求
if(HttpMethod.POST.equals(method)){
//..... } }catch(Exception e){
System.out.println("处理请求失败!");
e.printStackTrace();
}finally{
httpRequest.release();
}
} /*
* 建立连接时,返回消息
*/
@Override
public void channelActive(ChannelHandlerContext ctx)
throws Exception {
System.out.println("连接的客户端地址:"
+ ctx.channel().remoteAddress());
}
}
说明:
HttpServer.java就是实现一个http服务器,然后具体的handler入栈则是通过ServerHandlerInit.java实现。同时具体的http逻辑处理则是BusiHandler.java。
该示例实现了https的实现。
Netty实现简易http_server的更多相关文章
- Netty(四)基于Netty 的简易版RPC
3.1 RPC 概述 下面的这张图,大概很多小伙伴都见到过,这是 Dubbo 官网中的一张图描述了项目架构的演进过程 它描述了每一种架构需要的具体配置和组织形态.当网站流量很小时,只需一个应用,将所有 ...
- Netty(三)基于Bio和Netty 的简易版Tomcat
参考代码: https://github.com/FLGBetter/tomcat-rpc-demo
- Netty核心组件介绍及手写简易版Tomcat
Netty是什么: 异步事件驱动框架,用于快速开发高i性能服务端和客户端 封装了JDK底层BIO和NIO模型,提供高度可用的API 自带编码解码器解决拆包粘包问题,用户只用关心业务逻辑 精心设计的Re ...
- 使用Netty实现HTTP服务器
使用Netty实现HTTP服务器,使用Netty实现httpserver,Netty Http Netty是一个异步事件驱动的网络应用程序框架用于快速开发可维护的高性能协议服务器和客户端.Netty经 ...
- 2、Netty基础
一.前言 主要包含下面内容: 初识 Netty: 使用 Java NIO 搭建简单的客户端与服务端实现网络通讯: 使用 Netty 搭建简单的客户端与服务端实现网络通讯: Netty 底层操作与 Ja ...
- 阿里的Netty知识点你又了解多少
前言 Netty 是一个可以快速开发网络应用程序的 NIO 框架,它大大简化了 TCP 或者 UDP 服务器的网络编程.Netty 的简易和快速开发并不意味着由它开发的程序将失去可维护性或者存在性能问 ...
- 实现分布式服务注册及简易的netty聊天
现在很多地方都会用到zookeeper, 用到它的地方就是为了实现分布式.用到的场景就是服务注册,比如一个集群服务器,需要知道哪些服务器在线,哪些服务器不在线. ZK有一个功能,就是创建临时节点,当机 ...
- 基于Netty的RPC简易实现
代码地址如下:http://www.demodashi.com/demo/13448.html 可以给你提供思路 也可以让你学到Netty相关的知识 当然,这只是一种实现方式 需求 看下图,其实这个项 ...
- 一个简易的netty udp服务端
netty号称java高性能网络库,为人帮忙中,研究了下,写了一个demo.反复调试,更改,局域网两个客户端同时for循环发10000个20字节的数据包,入库mysql,居然没丢. 思路,netty的 ...
随机推荐
- python之内置函数与匿名函数
一内置函数 # print(abs(-1)) # print(all([1,2,'a',None])) # print(all([])) #bool值为假的情况:None,空,0,False # # ...
- 非关系型数据库&&缓存
面试其他篇 目录: 1.1
- php 输出缓存,每秒打印一个数字
<?php set_time_limit(0); //以上三行不加上nginx下不执行,一次性显示出来 header('Content-Type: text/event-stream'); // ...
- bzoj 3325 密码 - Manacher
题目传送门 需要root权限的传送点 题目大意 已知一个串,以每个字符为中心的最长回文串长,以及每两个字符中间为中心的最长回文串长.求字典序最小的这样一个串.题目保证有解. 考虑Manacher的过程 ...
- 让InstallShield 2015 Limited Edition for Visual Studio 2015生成的setup.exe双击时以管理员权限运行
转载:http://blog.csdn.net/zztoll/article/details/52096700 如题,如何让InstallShield 2015 Limited Edition for ...
- (转)ResNet, AlexNet, VGG, Inception: Understanding various architectures of Convolutional Networks
ResNet, AlexNet, VGG, Inception: Understanding various architectures of Convolutional Networks by KO ...
- 移动端开发:使用jQuery Mobile还是Zepto
原:http://blog.csdn.net/liubinwyzbt/article/details/51446771 jQuery Mobile和Zepto是移动端的js库.jQuery Mobil ...
- Codeforces 786 C. Till I Collapse
题目链接:http://codeforces.com/contest/786/problem/C 大力膜了一发杜教的代码感觉十分的兹瓷啊! 我们知道如果$k$是给定的我们显然是可以直接一遍$O(n)$ ...
- C#:CsvReader读取.CSV文件(转换成DataTable)
原文引用:https://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader using LumenWorks.Framework.IO.Csv; ...
- uoj #228. 基础数据结构练习题 线段树
#228. 基础数据结构练习题 统计 描述 提交 自定义测试 sylvia 是一个热爱学习的女孩子,今天她想要学习数据结构技巧. 在看了一些博客学了一些姿势后,她想要找一些数据结构题来练练手.于是她的 ...