当前位置: 首页 > news >正文

netty构建http服务器

Netty 是一个高性能的异步事件驱动的网络应用框架,用于快速开发可维护的高性能协议服务器和客户端。要使用 Netty 搭建一个支持 HTTP 方法(GET, POST, PUT, DELETE)的 HTTP 服务器,可以按照以下步骤进行操作。

准备工作

  1. 添加依赖:确保你的项目中包含了 Netty 的相关依赖。
  2. Java版本:确保你使用的 Java 版本支持 Netty,一般推荐使用 Java 8 或更高版本。

添加 Maven 依赖

在你的 pom.xml 文件中添加以下依赖:

<dependencies><dependency><groupId>io.netty</groupId><artifactId>netty-all</artifactId><version>4.1.95.Final</version></dependency>
</dependencies>

创建 HTTP 服务器

下面是一个简单的示例,展示了如何创建一个支持 GET, POST, PUT, DELETE 方法的 HTTP 服务器。

1. 定义 HTTP 请求处理器
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {@Overrideprotected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {if (!req.decoderResult().isSuccess()) {sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));return;}// 根据请求类型处理switch (req.method()) {case GET:handleGet(ctx, req);break;case POST:handlePost(ctx, req);break;case PUT:handlePut(ctx, req);break;case DELETE:handleDelete(ctx, req);break;default:sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.METHOD_NOT_ALLOWED));break;}}private void handleGet(ChannelHandlerContext ctx, FullHttpRequest req) {// 处理 GET 请求FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,Unpooled.copiedBuffer("This is a GET response", CharsetUtil.UTF_8));sendHttpResponse(ctx, req, response);}private void handlePost(ChannelHandlerContext ctx, FullHttpRequest req) {// 处理 POST 请求FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,Unpooled.copiedBuffer("This is a POST response", CharsetUtil.UTF_8));sendHttpResponse(ctx, req, response);}private void handlePut(ChannelHandlerContext ctx, FullHttpRequest req) {// 处理 PUT 请求FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,Unpooled.copiedBuffer("This is a PUT response", CharsetUtil.UTF_8));sendHttpResponse(ctx, req, response);}private void handleDelete(ChannelHandlerContext ctx, FullHttpRequest req) {// 处理 DELETE 请求FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,Unpooled.copiedBuffer("This is a DELETE response", CharsetUtil.UTF_8));sendHttpResponse(ctx, req, response);}private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {if (res.status().code() != 200) {ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);res.content().writeBytes(buf);buf.release();HttpHeaders.setContentLength(res, res.content().readableBytes());}// Generate an error page if response status code is not 200 (OK).if (res.status().code() != 200) {ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);res.content().writeBytes(buf);buf.release();}// Send the response and close the connection if necessary.ChannelFuture f = ctx.channel().writeAndFlush(res);if (!HttpHeaders.isKeepAlive(req) || res.status().code() != 200) {f.addListener(ChannelFutureListener.CLOSE);}}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {cause.printStackTrace();ctx.close();}
}
2. 启动服务器
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;public class HttpServer {public static void main(String[] args) throws InterruptedException {int port = 8080; // 选择一个端口EventLoopGroup bossGroup = new NioEventLoopGroup(1);EventLoopGroup workerGroup = new NioEventLoopGroup();try {ServerBootstrap b = new ServerBootstrap();b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new HttpServerInitializer());ChannelFuture f = b.bind(port).sync();System.out.println("HTTP server started on port " + port);f.channel().closeFuture().sync();} finally {bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}}
}
3. 初始化 Channel
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;public class HttpServerInitializer extends ChannelInitializer<SocketChannel> {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline p = ch.pipeline();p.addLast(new HttpResponseEncoder());p.addLast(new HttpRequestDecoder());p.addLast(new HttpObjectAggregator(65536));p.addLast(new HttpServerHandler());}
}

以上代码提供了一个基本的 HTTP 服务器框架,你可以根据需要添加具体的业务逻辑处理,如错误处理、日志记录、文件上传等高级功能。

在 Netty 中处理文件上传通常涉及到对 HTTP 请求中的 multipart/form-data 类型的解析。这种类型的请求通常用于上传文件和其他表单数据。下面介绍如何使用 Netty 和第三方库来处理文件上传。

第三方库

对于文件上传的支持,我们可以使用 netty-http2 项目中的 netty-codec-http2 依赖或者使用 netty-file-upload 项目中的 netty-codec-http 依赖,后者提供了更直接的方式来处理文件上传。我们将使用 netty-codec-http 依赖。

首先,在你的 pom.xml 文件中添加如下依赖:

<dependencies><dependency><groupId>io.netty</groupId><artifactId>netty-all</artifactId><version>4.1.95.Final</version></dependency><dependency><groupId>io.netty</groupId><artifactId>netty-codec-http</artifactId><version>4.1.95.Final</version></dependency><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.4</version></dependency>
</dependencies>

文件上传处理

  1. HTTP 请求解析器:使用 HttpDataFactoryHttpPostRequestDecoder 解析上传的数据。
  2. 文件保存:定义一个方法来保存上传的文件。
更新 HttpServerHandler
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {@Overrideprotected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {if (!req.decoderResult().isSuccess()) {sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));return;}switch (req.method()) {case GET:handleGet(ctx, req);break;case POST:handlePost(ctx, req);break;case PUT:handlePut(ctx, req);break;case DELETE:handleDelete(ctx, req);break;default:sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.METHOD_NOT_ALLOWED));break;}}private void handlePost(ChannelHandlerContext ctx, FullHttpRequest req) {if (!req.headers().contains(HttpHeaderNames.CONTENT_TYPE)) {sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));return;}String contentType = req.headers().get(HttpHeaderNames.CONTENT_TYPE);if (contentType.contains("multipart/form-data")) {handleFileUpload(ctx, req);} else {handleRegularPost(ctx, req);}}private void handleFileUpload(ChannelHandlerContext ctx, FullHttpRequest req) {FileUpload fileUpload = new FileUpload(new DiskFileItemFactory());HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(fileUpload, req);while (true) {try {HttpPostRequestDecoder.State state = decoder.decode(ctx.channel(), req, ctx.alloc().buffer());if (state == HttpPostRequestDecoder.State.END_OF_MESSAGE) {break;}if (state == HttpPostRequestDecoder.State.CHUNKED_INPUT) {decoder.offer(req);}} catch (HttpPostRequestDecoder.EndOfDataDecoderException e) {break;} catch (HttpPostRequestDecoder.ErrorDataDecoderException e) {sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));return;}}FileItemIterator iterator = decoder.getBodyHttpData();while (iterator.hasNext()) {FileItemStream item = iterator.next();if (item.isFormField()) {// Handle form fields here} else {saveUploadedFile(item, "/tmp/uploaded"); // Save the file to disk}}FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,Unpooled.copiedBuffer("File uploaded successfully.", CharsetUtil.UTF_8));sendHttpResponse(ctx, req, response);}private void saveUploadedFile(FileItemStream item, String uploadDir) throws IOException {Path targetPath = Path.of(uploadDir, item.getName());Files.createDirectories(targetPath.getParent());try (FileItemStream.ItemStream stream = item.openStream()) {Files.copy(stream, targetPath, StandardCopyOption.REPLACE_EXISTING);}}private void handleRegularPost(ChannelHandlerContext ctx, FullHttpRequest req) {// Handle regular POST data hereFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,Unpooled.copiedBuffer("This is a POST response", CharsetUtil.UTF_8));sendHttpResponse(ctx, req, response);}private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {// ... [same as before]}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {cause.printStackTrace();ctx.close();}
}

注意事项

  • 在这个示例中,我们使用了 commons-fileupload 库来处理 multipart/form-data 数据。
  • 上传的文件被保存到 /tmp/uploaded 目录下。你需要确保这个目录存在并且有适当的权限。
  • 我们使用了 DiskFileItemFactoryFileUpload 来处理文件上传。
  • 如果上传的文件非常大,你可能需要调整 DiskFileItemFactory 的配置以适应你的需求。

以上代码提供了一个基本的文件上传处理机制。你可以根据实际需要进一步扩展和优化。例如,可以添加文件大小限制、文件类型检查等功能。

相关文章:

netty构建http服务器

Netty 是一个高性能的异步事件驱动的网络应用框架&#xff0c;用于快速开发可维护的高性能协议服务器和客户端。要使用 Netty 搭建一个支持 HTTP 方法&#xff08;GET, POST, PUT, DELETE&#xff09;的 HTTP 服务器&#xff0c;可以按照以下步骤进行操作。 准备工作 添加依赖…...

Docker中安装Kafka和Kafka UI管理界面

Kafka 简介 Apache Kafka 是一个分布式流处理平台,主要用于构建实时数据管道和流应用。它最初由LinkedIn开发,并于2011年开源,之后成为Apache项目的一部分。Kafka的核心概念和功能包括: 发布与订阅消息系统:Kafka允许用户发布和订阅消息流。高吞吐量:Kafka能够处理大量数…...

防火墙——SNAT和DNAT策略的原理及应用、防火墙规则的备份、还原和抓包

防火墙——SNAT和DNAT策略的原理及应用、防火墙规则的备份、还原和抓包 &#x1f49d;&#x1f49d;&#x1f49d;欢迎来到我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&…...

C# 冒泡排序

栏目总目录 概念 冒泡排序&#xff08;Bubble Sort&#xff09;是一种简单的排序算法&#xff0c;它通过重复遍历待排序的数列&#xff0c;比较每对相邻的项&#xff0c;并在顺序错误时交换它们的位置&#xff0c;直到没有需要交换的项为止。由于排序过程中小数逐渐“浮”到前…...

网络传输层——UDP与TCP

前言&#xff1a; 1.国际网络体系结构&#xff1a; OSI模型: open system interconnect 理论模型 1977 国际标准化组织 各种不同体系结构的计算机能在世界范围内互联成网。 应用层:要传输的数据信息&#xff0c;如文件传输&#xff0c;电子邮件等…...

Hype 4 Pro for Mac:专业级HTML5动画制作利器

Hype 4 Pro for Mac是一款专为Mac用户设计的专业级HTML5动画制作软件&#xff0c;它集动画制作、交互设计于一身&#xff0c;为用户提供了一种全新的、高效的动画制作体验。 该软件拥有直观易用的界面和强大的功能&#xff0c;支持多种设计元素&#xff0c;如滚动、旋转、缩放…...

C++ STL remove, remove_if 用法

一&#xff1a;功能 移除序列中&#xff08;满足给定条件&#xff09;的元素&#xff0c;该操作并不是真的将元素删除&#xff0c;而是序列的size不变&#xff0c;只是更新了迭代器&#xff0c;该函数会返回最后一个未删除元素的位置。 二&#xff1a;用法 #include <vect…...

HarmonyOS NEXT 开发之ArkTS基础入门

ArkTS 是 HarmonyOS NEXT 的开发语言&#xff0c;它基于 TypeScript 并进行了扩展和优化。以下是一些基础语法知识点、示例用法及注意事项。 一、ArkTS 简介 ArkTS 是一种基于 TypeScript 的编程语言&#xff0c;主要用于 HarmonyOS 应用的 UI 界面和业务逻辑开发。它在 Type…...

UE5 C++跑酷练习(Part2)

一.首先GameMode里有Actor数组&#xff0c;组装直线路&#xff0c;和左右路 #include "CoreMinimal.h" #include "GameFramework/GameModeBase.h" #include "RunGANGameMode.generated.h"UCLASS(minimalapi) class ARunGANGameMode : public AG…...

从0开始搭建vue + flask 旅游景点数据分析系统(二):搭建基础框架

这一期目标是把系统的布局给搭建起来&#xff0c;采用一个非常简单的后端管理风格&#xff0c;可以参考官方的页面 https://element.eleme.cn/#/zh-CN/component/container 下面我们开始搭建&#xff0c;首先&#xff0c;安装一下vue-router&#xff0c;element-ui npm insta…...

【过滤器 vs 拦截器】SpringBoot中过滤器与拦截器:明智选择的艺术(如何在项目中做出明智选择)

文章目录 SpringBoot 过滤器 vs 拦截器过滤器 (Filter)定义特点使用场景实现步骤创建过滤器类注册过滤器&#xff08;可选&#xff0c;如果不使用 WebFilter 注解&#xff09; 拦截器 (Interceptor)定义特点使用场景实现步骤创建拦截器类注册拦截器 过滤器与拦截器的比较实际项…...

2024-06学习笔记

1.事务与数据库链接的占用 如果用Transactional注解&#xff0c;那在第一次与数据库交互的时候&#xff0c;就会打开数据库链接&#xff0c;再整个方法执行完&#xff0c;才会关闭数据库链接。 即使后边用的事务传播是required_new,那之前的事务也是被挂起&#xff0c;不会被…...

【VUE】封装一个追随鼠标的漂浮组件框架

红色箭头代表鼠标位置&#xff0c;蓝色区域跟随鼠标出现&#xff0c;鼠标进行其他操作的时候&#xff0c;蓝色区域隐藏。 vue全码 <template><divmousemove"updatePosition"mouseleave"hideDiv"class"container":style"{ positi…...

mapstruct与lombok结合使用

问题 如果同时使用mapstruct与lombok&#xff0c;需要多添加一个lombok支持mapstruct的依赖库。 解决 <dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId> </dependency><dependency><groupId&…...

【SpringBoot】Web开发之URL映射

RequestMapping("/getDataById/{id}") public String getDataById(PathVariable("id") Long id){ return "getDataById:"id; }46 如果URL中的参数名称与方法中的参数名称一致&#xff0c;则可以简化为&#xff1a; RequestMapping("/get…...

对递归的一些理解。力扣206题:翻转链表

今天在刷力扣的时候&#xff0c;在写一道翻转链表的题目的过程中&#xff0c;在尝试使用递归解决该问题的时候&#xff0c;第一版代码却每次都返回的是null&#xff0c;这个错误让我尝试去debug了一下&#xff0c;最终找出了问题&#xff0c;并且让我对递归有了一些更深的理解&…...

Kafka面试三道题

针对Kafka的面试题&#xff0c;从简单到困难&#xff0c;我可以给出以下三道题目&#xff1a; 1. Kafka的基本概念与优势 问题&#xff1a;请简要介绍Kafka是什么&#xff0c;并说明它相比传统消息队列的优势有哪些&#xff1f; 答案&#xff1a; Kafka定义&#xff1a;Apa…...

C/C++编程-算法学习-数字滤波器

数字滤波器 一阶低通滤波器结论推导11. 基本公式推导2. 截止频率 和 采样频率 推导 实现 二阶低通滤波器实现1实现2 一阶低通滤波器 结论 其基本原理基于以下公式&#xff1a; o u t p u t [ n ] α ∗ i n p u t [ n ] ( 1 − α ) ∗ o u t p u t [ n − 1 ] output[n] …...

maven介绍 搭建Nexus3(maven私服搭建)

Maven是一个强大的项目管理工具&#xff0c;它基于项目对象模型&#xff08;POM&#xff1a;Project Object Model&#xff09;的概念&#xff0c;通过XML格式的配置文件&#xff08;pom.xml&#xff09;来管理项目的构建 Maven确实可以被视为一种工程管理工具或项目自动化构…...

电商项目之如何判断线程池是否执行完所有任务

文章目录 1 问题背景2 前言3 4种常用的方法4 代码4.1 isTerminated()4.2 线程池的任务总数是否等于已执行的任务数4.3 CountDownLatch计数器4.4 CyclicBarrier计数器 1 问题背景 真实生产环境的电商项目&#xff0c;常使用线程池应用于执行大批量操作达到高性能的效果。应用场景…...

[2025CVPR]DeepVideo-R1:基于难度感知回归GRPO的视频强化微调框架详解

突破视频大语言模型推理瓶颈,在多个视频基准上实现SOTA性能 一、核心问题与创新亮点 1.1 GRPO在视频任务中的两大挑战 ​安全措施依赖问题​ GRPO使用min和clip函数限制策略更新幅度,导致: 梯度抑制:当新旧策略差异过大时梯度消失收敛困难:策略无法充分优化# 传统GRPO的梯…...

工业安全零事故的智能守护者:一体化AI智能安防平台

前言&#xff1a; 通过AI视觉技术&#xff0c;为船厂提供全面的安全监控解决方案&#xff0c;涵盖交通违规检测、起重机轨道安全、非法入侵检测、盗窃防范、安全规范执行监控等多个方面&#xff0c;能够实现对应负责人反馈机制&#xff0c;并最终实现数据的统计报表。提升船厂…...

PPT|230页| 制造集团企业供应链端到端的数字化解决方案:从需求到结算的全链路业务闭环构建

制造业采购供应链管理是企业运营的核心环节&#xff0c;供应链协同管理在供应链上下游企业之间建立紧密的合作关系&#xff0c;通过信息共享、资源整合、业务协同等方式&#xff0c;实现供应链的全面管理和优化&#xff0c;提高供应链的效率和透明度&#xff0c;降低供应链的成…...

前端导出带有合并单元格的列表

// 导出async function exportExcel(fileName "共识调整.xlsx") {// 所有数据const exportData await getAllMainData();// 表头内容let fitstTitleList [];const secondTitleList [];allColumns.value.forEach(column > {if (!column.children) {fitstTitleL…...

质量体系的重要

质量体系是为确保产品、服务或过程质量满足规定要求&#xff0c;由相互关联的要素构成的有机整体。其核心内容可归纳为以下五个方面&#xff1a; &#x1f3db;️ 一、组织架构与职责 质量体系明确组织内各部门、岗位的职责与权限&#xff0c;形成层级清晰的管理网络&#xf…...

基础测试工具使用经验

背景 vtune&#xff0c;perf, nsight system等基础测试工具&#xff0c;都是用过的&#xff0c;但是没有记录&#xff0c;都逐渐忘了。所以写这篇博客总结记录一下&#xff0c;只要以后发现新的用法&#xff0c;就记得来编辑补充一下 perf 比较基础的用法&#xff1a; 先改这…...

Spring Boot面试题精选汇总

&#x1f91f;致敬读者 &#x1f7e9;感谢阅读&#x1f7e6;笑口常开&#x1f7ea;生日快乐⬛早点睡觉 &#x1f4d8;博主相关 &#x1f7e7;博主信息&#x1f7e8;博客首页&#x1f7eb;专栏推荐&#x1f7e5;活动信息 文章目录 Spring Boot面试题精选汇总⚙️ **一、核心概…...

解决本地部署 SmolVLM2 大语言模型运行 flash-attn 报错

出现的问题 安装 flash-attn 会一直卡在 build 那一步或者运行报错 解决办法 是因为你安装的 flash-attn 版本没有对应上&#xff0c;所以报错&#xff0c;到 https://github.com/Dao-AILab/flash-attention/releases 下载对应版本&#xff0c;cu、torch、cp 的版本一定要对…...

C++ 求圆面积的程序(Program to find area of a circle)

给定半径r&#xff0c;求圆的面积。圆的面积应精确到小数点后5位。 例子&#xff1a; 输入&#xff1a;r 5 输出&#xff1a;78.53982 解释&#xff1a;由于面积 PI * r * r 3.14159265358979323846 * 5 * 5 78.53982&#xff0c;因为我们只保留小数点后 5 位数字。 输…...

AspectJ 在 Android 中的完整使用指南

一、环境配置&#xff08;Gradle 7.0 适配&#xff09; 1. 项目级 build.gradle // 注意&#xff1a;沪江插件已停更&#xff0c;推荐官方兼容方案 buildscript {dependencies {classpath org.aspectj:aspectjtools:1.9.9.1 // AspectJ 工具} } 2. 模块级 build.gradle plu…...