当前位置: 首页 > 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;常使用线程池应用于执行大批量操作达到高性能的效果。应用场景…...

Java 语言特性(面试系列2)

一、SQL 基础 1. 复杂查询 &#xff08;1&#xff09;连接查询&#xff08;JOIN&#xff09; 内连接&#xff08;INNER JOIN&#xff09;&#xff1a;返回两表匹配的记录。 SELECT e.name, d.dept_name FROM employees e INNER JOIN departments d ON e.dept_id d.dept_id; 左…...

IGP(Interior Gateway Protocol,内部网关协议)

IGP&#xff08;Interior Gateway Protocol&#xff0c;内部网关协议&#xff09; 是一种用于在一个自治系统&#xff08;AS&#xff09;内部传递路由信息的路由协议&#xff0c;主要用于在一个组织或机构的内部网络中决定数据包的最佳路径。与用于自治系统之间通信的 EGP&…...

高频面试之3Zookeeper

高频面试之3Zookeeper 文章目录 高频面试之3Zookeeper3.1 常用命令3.2 选举机制3.3 Zookeeper符合法则中哪两个&#xff1f;3.4 Zookeeper脑裂3.5 Zookeeper用来干嘛了 3.1 常用命令 ls、get、create、delete、deleteall3.2 选举机制 半数机制&#xff08;过半机制&#xff0…...

Unsafe Fileupload篇补充-木马的详细教程与木马分享(中国蚁剑方式)

在之前的皮卡丘靶场第九期Unsafe Fileupload篇中我们学习了木马的原理并且学了一个简单的木马文件 本期内容是为了更好的为大家解释木马&#xff08;服务器方面的&#xff09;的原理&#xff0c;连接&#xff0c;以及各种木马及连接工具的分享 文件木马&#xff1a;https://w…...

Python 包管理器 uv 介绍

Python 包管理器 uv 全面介绍 uv 是由 Astral&#xff08;热门工具 Ruff 的开发者&#xff09;推出的下一代高性能 Python 包管理器和构建工具&#xff0c;用 Rust 编写。它旨在解决传统工具&#xff08;如 pip、virtualenv、pip-tools&#xff09;的性能瓶颈&#xff0c;同时…...

基于PHP的连锁酒店管理系统

有需要请加文章底部Q哦 可远程调试 基于PHP的连锁酒店管理系统 一 介绍 连锁酒店管理系统基于原生PHP开发&#xff0c;数据库mysql&#xff0c;前端bootstrap。系统角色分为用户和管理员。 技术栈 phpmysqlbootstrapphpstudyvscode 二 功能 用户 1 注册/登录/注销 2 个人中…...

Spring AI Chat Memory 实战指南:Local 与 JDBC 存储集成

一个面向 Java 开发者的 Sring-Ai 示例工程项目&#xff0c;该项目是一个 Spring AI 快速入门的样例工程项目&#xff0c;旨在通过一些小的案例展示 Spring AI 框架的核心功能和使用方法。 项目采用模块化设计&#xff0c;每个模块都专注于特定的功能领域&#xff0c;便于学习和…...

【Elasticsearch】Elasticsearch 在大数据生态圈的地位 实践经验

Elasticsearch 在大数据生态圈的地位 & 实践经验 1.Elasticsearch 的优势1.1 Elasticsearch 解决的核心问题1.1.1 传统方案的短板1.1.2 Elasticsearch 的解决方案 1.2 与大数据组件的对比优势1.3 关键优势技术支撑1.4 Elasticsearch 的竞品1.4.1 全文搜索领域1.4.2 日志分析…...

【C++】纯虚函数类外可以写实现吗?

1. 答案 先说答案&#xff0c;可以。 2.代码测试 .h头文件 #include <iostream> #include <string>// 抽象基类 class AbstractBase { public:AbstractBase() default;virtual ~AbstractBase() default; // 默认析构函数public:virtual int PureVirtualFunct…...

VSCode 使用CMake 构建 Qt 5 窗口程序

首先,目录结构如下图: 运行效果: cmake -B build cmake --build build 运行: windeployqt.exe F:\testQt5\build\Debug\app.exe main.cpp #include "mainwindow.h"#include <QAppli...