分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 运营维护

Netty实现简易http_server

发布时间:2023-09-06 02:18责任编辑:熊小新关键词:http

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(); ???????} ???}}
View Code

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()); ???}}
View Code

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()); ???}}
View Code

说明:

HttpServer.java就是实现一个http服务器,然后具体的handler入栈则是通过ServerHandlerInit.java实现。同时具体的http逻辑处理则是BusiHandler.java。

该示例实现了https的实现。

Netty实现简易http_server

原文地址:https://www.cnblogs.com/duanjt/p/9800317.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved