基于uWebSockets开源库实现一个web服务
一.uWebSockets简介
uWebSockets 是一款用 C++ 编写的高性能 Web 服务器库,专注于实时通信。它支持 WebSocket、HTTP/1.1 和 HTTP/2 协议,专为高并发、低延迟的实时应用设计.
核心特性
极致性能:基于异步 I/O 和事件驱动架构,单进程可处理数万并发连接,平均延迟低于 1ms。
低内存占用:通过内存池技术减少动态内存分配,适合大规模部署。
跨平台支持:兼容 Linux、Windows 等操作系统。
轻量级设计:直接处理 WebSocket 协议,避免多进程/线程的开销。
典型应用场景
高频交易系统:如订单实时推送。
物联网网关:设备状态同步。
在线多人游戏:实时动作广播。
与其他库对比
相较于 Node.js 和 Nginx,uWebSockets 在应用层直接处理协议,性能更优。其源码结构清晰,包含核心代码、示例程序和性能测试模块。
二.linux下uWebSockets编译
编译步骤
1.获取源代码
使用git克隆uWebSockets的主仓库
git clone https://github.com/uNetworking/uWebSockets.git
cd uWebSockets
2.处理依赖的子模块
uWebSockets依赖uSockets和libdeflate两个第三方库,需要手动下载并编译它们.
3.编译uWebSockets
在uWebSockets根目录下执行
三.qt下实现一个web服务
1)在.pro文件中添加uWebSockets依赖文件及依赖库
httpServer.pro内容如下:
QT -= guiCONFIG += c++17 console
CONFIG -= app_bundle# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0SOURCES += \main.cpp# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path