• 如何写一个简单的基于 Qt 框架的 HttpServer ?


    httpserver.h

    #ifndef HTTPSERVER_H
    #define HTTPSERVER_H
    
    #include <QObject>
    #include <QtCore>
    #include <QtNetwork>
    class HttpServer : public QObject
    {
        Q_OBJECT
    public:
        static HttpServer &instance();
        void run(const QHostAddress &address = QHostAddress::Any,const quint16 &port = 80);
    signals:
    
    public slots:
    private slots:
        void newConnection();
        void readyRead();
    private:
        explicit HttpServer(QObject *parent = nullptr);
        ~HttpServer();
        Q_DISABLE_COPY(HttpServer)
    private:
        QTcpServer *m_httpServer;
    };
    
    #endif // HTTPSERVER_H
    
    

    httpserver.cpp

    #include "httpserver.h"
    
    HttpServer &HttpServer::instance()
    {
        static HttpServer obj;
        return obj;
    }
    
    void HttpServer::run(const QHostAddress &address, const quint16 &port)
    {
        m_httpServer->listen(address,port);
    }
    
    void HttpServer::newConnection()
    {
        qDebug() << "newConnection";
        QTcpSocket *m_socket = m_httpServer->nextPendingConnection();
        QObject::connect(m_socket,&QTcpSocket::readyRead,this,&HttpServer::readyRead);
    }
    
    void HttpServer::readyRead()
    {
        QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
        if(socket){
            QByteArray request = socket->readAll();
    
            qDebug() << "Request Data:" << request;
    
            static int count = 0;
            count++;
            QByteArray response = QString("<h1><center>Hello World %1</center></h1>
    ").arg(count).toUtf8();
    
    
            QString http = "HTTP/1.1 200 OK
    ";
            http += "Server: nginx
    ";
            http += "Content-Type: text/html;charset=utf-8
    ";
            http += "Connection: keep-alive
    ";
            http += QString("Content-Length: %1
    
    ").arg(QString::number(response.size()));
    
            socket->write(http.toUtf8());
            socket->write(response);
            socket->flush();
            socket->waitForBytesWritten(http.size() + response.size());
            socket->close();
        }
    }
    
    HttpServer::HttpServer(QObject *parent) : QObject(parent)
    {
        m_httpServer = new QTcpServer(this);
        m_httpServer->setMaxPendingConnections(1024);//设置最大允许连接数
        QObject::connect(m_httpServer,&QTcpServer::newConnection,this,&HttpServer::newConnection);
    }
    
    HttpServer::~HttpServer()
    {
    
    }
    
    

    运行

    HttpServer::instance().run();
    

    访问 127.0.0.1 即可

  • 相关阅读:
    《C++ Primer》学习笔记第2章 变量和基本类型
    Java学习笔记类的继承与多态特性
    Java的冒泡排序问题
    新起点,分享,进步
    MVC2中Area的路由注册实现
    了解一下new关键字实现阻断继承的原理
    利用Bing API开发的搜索工具(MVC+WCF)
    ASP.NET MVC中错误处理方式
    const和readonly内部区别
    WCF中校验参数的实现方式(一)
  • 原文地址:https://www.cnblogs.com/cheungxiongwei/p/11011173.html
Copyright © 2020-2023  润新知