Qt开发的超轻量http server

    所谓http协议,本质上也是基于TCP/IP上服务器与客户端请求和应答的标准,web开发中常用的http server有apache和nginx。Qt程序作为http client可以使用QNetworkAccessManager很方便的进行http相关的操作。Qt本身并没有http server相关的库,也许是因为很少有这种需求吧,毕竟把一台嵌入式设备做http服务器也是挺奇怪。但是实际开发中也会有做简单的http server的需求,这里我们可以用Qt本身的QTcpServer仿制一个HttpServer。

Message::Message(QObject *parent) : QObject(parent)
{
    m_tcpServer = new QTcpServer(this);
    m_tcpServer->listen(QHostAddress::Any, 80);
    m_tcpServer->setMaxPendingConnections(1); //设置最大允许连接数
    connect(m_tcpServer, SIGNAL(newConnection()), this, SLOT(newConnectSlot()));
}

void Message::newConnectSlot()
{
    tcpSocket = m_tcpServer->nextPendingConnection();
    connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(getMessage()));
}

void Message::getMessage()
{
    QByteArray data = tcpSocket->readAll();
    qDebug() << data;
    postData();
}

void Message::postData()
{
    QFile file(":/1.jpg");
    if(!file.open(QIODevice::ReadOnly))
    {
        qDebug("open failed!");
        return;
    }

    QString http = "HTTP/1.1 200 OK\r\n";
    http += "Server: nginx\r\n";
    http += "Content-Type: application/octet-stream;charset=utf-8\r\n";
    http += "Connection: keep-alive\r\n";
    http += QString("Content-Length: %1\r\n\r\n").arg(QString::number(file.size()));

    if(tcpSocket != nullptr) {
        QByteArray headData, data;
        headData.append(http);
        tcpSocket->write(headData);

        while(!file.atEnd()) {
            data = file.read(10240);        //每次读取10k的数据,并发送
            tcpSocket->write(data);
        }
        qDebug("success");
    }
}

    想要读懂这些代码需要了解http协议,具体可以去百度,理解http协议最好的办法就是去抓包。这个demo是用来传输大文件,利用http协议传输json数据或字符串数据也是同样的道理。demo下载地址:https://download.csdn.net/download/a18373279153/10421258

猜你喜欢

转载自blog.csdn.net/a18373279153/article/details/80364320