用QT写一个服务器,用户通过客户端(如浏览器)输入 URL,客户端向服务器发起一个 HTTP 请求。
myhttpserver.h
#ifndef MYHTTPSERVER_H
#define MYHTTPSERVER_H
#include <QObject>
#include<QTcpServer>
#include<QTcpSocket>
class myhttpserver : public QObject
{
Q_OBJECT
public:
explicit myhttpserver(QObject *parent = nullptr);
~myhttpserver();
signals:
public slots:
void dealConnection();
private:
QTcpSocket *socket;
QTcpServer *server;
};
#endif // MYHTTPSERVER_H
myhttpserver.cpp
#include "myhttpserver.h"
#include<QDebug>
myhttpserver::myhttpserver(QObject *parent) : QObject(parent)
{
server=new QTcpServer(this);
socket=nullptr;
bool isok=server->listen(QHostAddress::Any,8080);
if(!isok)
{
qDebug()<<"致命错误,web服务器没有开启成功!";
}
else
{
qDebug()<<"正常启动,web服务器端口为8080,等待客户端的连接.....";
}
connect(server,&QTcpServer::newConnection,this,&myhttpserver::dealConnection);
}
myhttpserver::~myhttpserver()
{
socket->close();
}
void myhttpserver::dealConnection()
{
socket=server->nextPendingConnection();
//堵塞直到通信套接字可以读到消息
while(!socket->waitForReadyRead(100));
char webdata[1024];
socket->read(webdata,1024);
qDebug()<<"正常运行:从浏览器读取数据信息......"<<QString(webdata);
// 使用 QString 构建 HTTP 响应
QString response;
response += "HTTP/1.1 200 OK\r\n";
response += "Content-Type: text/html; charset=utf-8\r\n";
response += "Connection: close\r\n";
response += "Refresh: 3\r\n\r\n";
response += "<!DOCTYPE html>"
"<html>"
"<head>"
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>"
"<title>HttpServer</title>"
"</head>"
"<body>客户端已经连接HttpServer服务器秒数为:";
static qint16 icount = 0; // 用于在浏览器上显示的统计访问数字
response += QString::number(icount++);
response += "</body>"
"</html>";
// 发送响应
QByteArray responseBytes = response.toUtf8();
socket->write(responseBytes);
// 刷新输出缓冲区(通常不是必需的,因为write()已经发送了数据)
socket->flush();
// 连接断开信号到删除套接字
connect(socket, &QTcpSocket::disconnected, socket, &QTcpSocket::deleteLater);
// 断开与主机的连接(通常不是必需的,因为当套接字断开连接时,它会自动关闭)但在这里为了刷新需要断开连接
socket->disconnectFromHost();
}
main.cpp
#include <QCoreApplication>
#include "myhttpserver.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
myhttpserver servers;
return a.exec();
}
运行图片