【QT】HTTP服务器
QTcpServer类
QTcpServer是Qt网络模块中的一个网络通信类,它提供了一个简单而强大的方式来实现服务器端的网络通信,使开发者能够轻松地创建TCP服务器应用程序
特点
- 监听和处理连接请求:QTcpServer允许应用程序监听并处理传入的TCP连接请求。它能够在指定的IP地址和端口上开始监听,当有新的客户端连接时,会发出newConnection信号。
- 并发处理:QTcpServer能够处理多个客户端同时连接,通过多线程或事件循环等机制实现并发处理,从而提高服务器端的性能和效率。
- 简化网络编程:QTcpServer封装了TCP协议的复杂细节,提供了更高级别的接口,简化了网络编程的复杂性。开发者无需深入了解TCP协议的底层细节,即可实现网络通信。
- 灵活的事件处理:QTcpServer通过信号和槽机制处理连接建立、断开、数据到达等事件,实现了灵活的连接管理和数据处理。
函数
- 构造函数:QTcpServer(QObject *parent = nullptr)用于创建一个QTcpServer对象。
- listen:bool listen(const QHostAddress &address = QHostAddress::Any, quint16 port = 0)用于在指定的地址和端口上监听传入的连接请求。
- close:void close()用于停止服务器,并断开所有现存连接。
- isListening:bool isListening() const用于判断服务器是否正在监听。
- nextPendingConnection:QTcpSocket *nextPendingConnection()用于返回下一个等待处理的客户端连接。
- maxPendingConnections:int maxPendingConnections() const用于返回最大待处理连接数。
- setMaxPendingConnections:void setMaxPendingConnections(int numConnections)用于设置最大待处理连接数。
- hasPendingConnections:bool hasPendingConnections() const用于判断是否有待处理的客户端连接。
- serverAddress:QHostAddress serverAddress() const用于返回服务器的地址。
- serverPort:quint16 serverPort() const用于返回服务器的端口。
- errorString:QString errorString() const用于返回最后一个错误的描述
信号
- newConnection:当有新的客户端连接时发出此信号。
- acceptError:当接受连接时发生错误时发出此信号。
创建HTPP服务
创建服务
QTcpServer* tcpServer = new QTcpServer(this);
connect(tcpServer, SIGNAL(newConnection()), this, SLOT(newClient())); //连接客户端
tcpServer->listen(QHostAddress(ip), port); // 设置地址和端口监听传入的请求
获取客户端
void MainWindow::newClient()
{
// 连接客户端
QTcpSocket* clientSocket = tcpServer->nextPendingConnection();
connect(clientSocket, &QTcpSocket::readyRead, this, &MainWindow::readDatagram);
// 当客户端断开连接时,需要确保及时释放与客户端通信的QTcpSocket对象所占用的资源
connect(clientSocket, &QTcpSocket::disconnected, clientSocket, &QTcpSocket::deleteLater);
logger->log("Socket 连接成功");
}
解析客户端传入的http请求 post get
// 构件http响应
QByteArray buildHttpResponse(const QByteArray& body, int statusCode)
{
QString statusLine = QString("HTTP/1.1 %1 OK\r\n").arg(statusCode);
QByteArray response = statusLine.toUtf8();
response += "Content-Type: application/json\r\n";
response += "Content-Length: " + QByteArray::number(body.size()) + "\r\n";
response