首页 技术 正文
技术 2022年11月16日
0 收藏 446 点赞 3,349 浏览 4255 个字

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的实现。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,489
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,904
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,737
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,490
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,128
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,291