QTcpServer实现web静态资源服务
使用 QTcpServer
实现web静态资源服务
目标:
- 监听 8080 端口,处理浏览器的 HTTP 请求。
- 默认返回
index.html
,路径/
对应该文件。 - 响应其他静态文件(HTML、CSS、JS、图片等)。
- 文件不存在时,返回 404 错误。
实现步骤:
- 启动服务器:使用
QTcpServer::listen(QHostAddress::Any, 8080)
监听 8080 端口。 - 解析请求路径:从 HTTP 请求中提取路径。默认路径
/
对应/index.html
。 - 返回静态文件:读取文件并根据扩展名设置
Content-Type
,然后通过socket
返回内容。 - 错误处理:当文件不存在时,返回
404 Not Found
。
示例代码:
#include <QTcpServer>
#include <QTcpSocket>
#include <QFile>
#include <QDir>
class HttpServer : public QTcpServer {
Q_OBJECT
public:
// 构造函数:启动监听8080端口
HttpServer() {
listen(QHostAddress::Any, 8080);
}
protected:
// 重写incomingConnection,用于处理新连接
void incomingConnection(qintptr socketDescriptor) override {
QTcpSocket *socket = new QTcpSocket(this);
socket->setSocketDescriptor(socketDescriptor); // 设置套接字描述符
// 处理来自客户端的请求
connect(socket, &QTcpSocket::readyRead, this, [this, socket]() {
QString request = socket->readAll(); // 读取请求内容
QString path = parseRequestPath(request); // 解析请求路径
if (path.isEmpty() || path == "/") path = "/index.html"; // 默认返回index.html
QString filePath = QDir::currentPath() + "/build" + path; // 构建文件路径
QFile file(filePath);
// 如果文件存在并且可以打开,发送文件内容
if (file.exists() && file.open(QIODevice::ReadOnly)) {
sendFile(socket, file, path);
} else {
// 文件不存在,返回404错误
socket->write("HTTP/1.1 404 Not Found\r\n\r\n");
}
socket->disconnectFromHost(); // 处理完成后断开连接
});
// 断开连接时,自动删除socket对象
connect(socket, &QTcpSocket::disconnected, socket, &QTcpSocket::deleteLater);
}
private:
// 解析HTTP请求,提取请求路径
QString parseRequestPath(const QString &request) {
return request.split("\r\n").first().split(" ").value(1); // 解析第一行,提取路径部分
}
// 发送文件内容给客户端,并设置正确的Content-Type
void sendFile(QTcpSocket *socket, QFile &file, const QString &path) {
QByteArray response = "HTTP/1.1 200 OK\r\n"; // 构建HTTP响应头
if (path.endsWith(".html")) response += "Content-Type: text/html\r\n";
else if (path.endsWith(".css")) response += "Content-Type: text/css\r\n";
else if (path.endsWith(".js")) response += "Content-Type: application/javascript\r\n";
response += "\r\n" + file.readAll(); // 读取文件内容并添加到响应体
socket->write(response); // 发送响应
}
};
伪代码,仅提供参考!
说明:
- 监听端口 8080。
- 处理根路径
/
,返回index.html
。 - 支持静态文件类型(HTML、CSS、JS)。
- 404 处理:文件不存在返回
404 Not Found
。
总结:
使用 QTcpServer
实现了基本的 HTTP 请求处理,并且可以响应静态文件,用于前端项目打包后的静态资源服务。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
2023-09-11 如何从 Mapbox 获取缩放级别的比例?
2023-09-11 Postgresq l 数据库查询格式为jsonp的列,怎么查询其值属性 | ->> 操作符
2023-09-11 PostgreSQL 的@>与<@运算符