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的实现。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗