mirror of
https://github.com/Light-City/CPlusPlusThings.git
synced 2026-10-28 19:04:45 +08:00
- const README: rewrite the space-saving claim per issue #5 follow-ups (constant-expression const vs #define immediates; which const qualify as constant expressions) - const README: fix the class-section diagnosis per issue #338 (overload resolution picks the const overload; the restriction only surfaces once that overload is removed) - sizeof README: virtual-inheritance result is compiler-dependent (GCC merges vbptr+vfptr -> 16, MSVC keeps them separate -> 32) #246 - static README: new section on internal linkage / access restriction with anonymous-namespace comparison #142 - 10-day practice: full problem list table + fixed day links #136 - new design_pattern/singleton/singleton_default.hpp: reusable thread-safe CRTP singleton template, compile+concurrency tested #303
37 lines
2.1 KiB
Markdown
37 lines
2.1 KiB
Markdown
> 来自 [C++那些事网站](https://light-city.github.io/stories_things/cpp-projects/modern-cpp-http-server/) 的文章,由站点同步脚本导出。
|
||
|
||
# C++20 协程 HTTP 服务器
|
||
|
||
## 现代 C++ HTTP 服务器
|
||
|
||
最近星球小伙伴总是问我有没有网络相关的项目,于是写了一个基于现代C++ + CMake管理的完整项目。
|
||
|
||
该项目具备以下特性:
|
||
|
||
- 大量现代C++特性
|
||
- C++20相关
|
||
- cortouine
|
||
- concept
|
||
- std::format
|
||
- std::span
|
||
- C++17相关
|
||
- if语句初始化
|
||
- 结构化绑定
|
||
- optional
|
||
- 高效的事件驱动机制
|
||
- 使用 `epoll` 实现事件循环,管理大量的客户端连接。`epoll` 是 Linux 平台上处理高并发 I/O 的高效工具,它可以同时监听多个文件描述符的事件,从而有效地减少系统调用开销,提高 I/O 操作的并发性。
|
||
- 服务器在主事件循环中通过非阻塞 `epoll_wait` 监听连接事件,避免了传统阻塞 I/O 带来的性能瓶颈。
|
||
- 协程与异步编程
|
||
- 采用 C++20 协程简化异步任务的实现,提供了类似同步代码的写法,使代码逻辑更加清晰。项目中通过 `co_await` 异步读取和写入客户端数据,减少了线程上下文切换的开销。
|
||
- 实现了 `SocketAwaiter` 和 `AsyncSocketOperation` 两个类,用于封装套接字的异步读写操作,使得编写异步处理代码变得更加简洁和自然。
|
||
- 文件 I/O 操作的异步处理
|
||
- 服务器支持异步读取 HTML 文件内容,通过 `std::async` 实现异步文件读取,避免阻塞主线程,从而更快地响应客户端请求。
|
||
- 在处理请求时,异步读取所需的文件并缓存到内存,减少了 I/O 操作对性能的影响。
|
||
- 非阻塞套接字操作
|
||
- 使用 `fcntl` 将套接字设置为非阻塞模式,保证 `accept` 和 `read/write` 操作不会阻塞服务器的主线程。这在高并发场景下尤为重要,可以显著提高服务器的并发处理能力。
|
||
|
||
项目效果:
|
||
|
||
|
||
|
||
学习方式:有详细的文档+代码,可以单独购买加下方微信或者加入星球即可。 |