当前位置: 代码网 > it编程>编程语言>C/C++ > 详解Qt如何使用QtWebApp搭建Http服务器

详解Qt如何使用QtWebApp搭建Http服务器

2024年12月30日 C/C++ 我要评论
一、qtwebapp源码下载a 、下载地址http://www.stefanfrings.de/qtwebapp/qtwebapp.zipb、 源码目录二、http服务器搭建a、使用qt create

一、qtwebapp源码下载

a 、下载地址

http://www.stefanfrings.de/qtwebapp/qtwebapp.zip

b、 源码目录

二、http服务器搭建

a、使用qt creater新建一个项目

b、将qtwebapp的源码拷贝到工程中

c、新建一个httpserver的类,继承stefanfrings::httprequesthandler

需要包含相关头文件

#include <qobject>
#include "httpserver/httprequesthandler.h"
#include <qsettings>
#include "httpserver/httplistener.h"	//新增代码
#include "httpserver/httprequesthandler.h"	//新增代码
#include "httpserver/staticfilecontroller.h"
#include "httpserver.h"
#include <qfile>
#include <qfileinfo>

httpserver.h

#ifndef httpserver_h
#define httpserver_h

#include <qobject>
#include "httpserver/httprequesthandler.h"
#include <qsettings>
#include "httpserver/httplistener.h"	//新增代码
#include "httpserver/httprequesthandler.h"	//新增代码
#include "httpserver/staticfilecontroller.h"
#include "httpserver.h"
#include <qfile>
#include <qfileinfo>

class httpserver : public stefanfrings::httprequesthandler
{
    q_object
public:
    explicit httpserver(qobject *parent = nullptr);
    void service(stefanfrings::httprequest& request, stefanfrings::httpresponse& response);

    /** encoding of text files */
    qstring encoding;

    /** root directory of documents */
    qstring docroot;

    /** maximum age of files in the browser cache */
    int maxage;

    struct cacheentry {
        qbytearray document;
        qint64 created;
        qbytearray filename;
    };

    /** timeout for each cached file */
    int cachetimeout;

    /** maximum size of files in cache, larger files are not cached */
    int maxcachedfilesize;

    /** cache storage */
    qcache<qstring,cacheentry> cache;

    /** used to synchronize cache access for threads */
    qmutex mutex;
};

#endif // httpserver_h

httpserver.cpp

#include "httpserver.h"

httpserver::httpserver(qobject *parent)
    : httprequesthandler{parent}
{

    qstring configfilename=":/new/prefix1/webapp.ini";
    qsettings* listenersettings=new qsettings(configfilename, qsettings::iniformat, this);
    listenersettings->begingroup("listener");	//新增代码

    new stefanfrings::httplistener(listenersettings, this, this);	//新增代码

    docroot = "e:/qt/learning/httpserver/httpserver";
}

void httpserver::service(stefanfrings::httprequest &request, stefanfrings::httpresponse &response)
{
    qbytearray path=request.getpath();
    // check if we have the file in cache
    qint64 now=qdatetime::currentmsecssinceepoch();
    mutex.lock();
    cacheentry* entry=cache.object(path);
    if (entry && (cachetimeout==0 || entry->created>now-cachetimeout))
    {
        qbytearray document=entry->document; //copy the cached document, because other threads may destroy the cached entry immediately after mutex unlock.
        qbytearray filename=entry->filename;
        mutex.unlock();
        qdebug("staticfilecontroller: cache hit for %s",path.data());
        response.setheader("content-type", "application/x-zip-compressed");
        response.setheader("cache-control","max-age="+qbytearray::number(maxage/1000));
        response.write(document,true);
    }
    else
    {
        mutex.unlock();
        // the file is not in cache.
        qdebug("staticfilecontroller: cache miss for %s",path.data());
        // forbid access to files outside the docroot directory
        if (path.contains("/.."))
        {
            qwarning("staticfilecontroller: detected forbidden characters in path %s",path.data());
            response.setstatus(403,"forbidden");
            response.write("403 forbidden",true);
            return;
        }
        // if the filename is a directory, append index.html.
        if (qfileinfo(docroot+path).isdir())
        {
            response.setstatus(404,"not found");
            response.write("404 not found",true);
            return;
        }
        // try to open the file
        qfile file(docroot+path);
        qdebug("staticfilecontroller: open file %s",qprintable(file.filename()));
        if (file.open(qiodevice::readonly))
        {
            response.setheader("content-type", "application/x-zip-compressed");
            response.setheader("cache-control","max-age="+qbytearray::number(maxage/1000));
            response.setheader("content-length",qbytearray::number(file.size()));
            if (file.size()<=maxcachedfilesize)
            {
                // return the file content and store it also in the cache
                entry=new cacheentry();
                while (!file.atend() && !file.error())
                {
                    qbytearray buffer=file.read(65536);
                    response.write(buffer);
                    entry->document.append(buffer);
                }
                entry->created=now;
                entry->filename=path;
                mutex.lock();
                cache.insert(request.getpath(),entry,entry->document.size());
                mutex.unlock();
            }
            else
            {
                // return the file content, do not store in cache
                while (!file.atend() && !file.error())
                {
                    response.write(file.read(65536));
                }
            }
            file.close();
        }
        else {
            if (file.exists())
            {
                qwarning("staticfilecontroller: cannot open existing file %s for reading",qprintable(file.filename()));
                response.setstatus(403,"forbidden");
                response.write("403 forbidden",true);
            }
            else
            {
                response.setstatus(404,"not found");
                response.write("404 not found",true);
            }
        }
    }

}

程序中

    qstring configfilename=":/new/prefix1/webapp.ini";
    qsettings* listenersettings=new qsettings(configfilename, qsettings::iniformat, this);
    listenersettings->begingroup("listener");	//新增代码

    new stefanfrings::httplistener(listenersettings, this, this);	//新增代码

    docroot = "e:/qt/learning/httpserver/httpserver";

configfilename为配置文件内容如下:

[listener]
;host=127.0.0.1
port=8080
minthreads=4
maxthreads=100
cleanupinterval=60000
readtimeout=60000
maxrequestsize=16000
maxmultipartsize=10000000

[docroot]
path=e:/qt/learning/httpserver/httpserver
encoding=utf-8
maxage=60000
cachetime=60000
cachesize=1000000
maxcachedfilesize=65536

docroot 为文件的根目录

三、启动http服务器

在mainwindow中新建一个httpserver 变量,然后实例化,

此时http服务器已经启动了。

四、获取http服务器文件

a、打开浏览器输入http://localhost:8080/filename就能下载到文件名为filename的文件了。

b、我的程序中只实现了zip文件,如果是其他类型文件需要修改一下地方

void staticfilecontroller::setcontenttype(const qstring filename, httpresponse &response) const
{
    if (filename.endswith(".png"))
    {
        response.setheader("content-type", "image/png");
    }
    else if (filename.endswith(".jpg"))
    {
        response.setheader("content-type", "image/jpeg");
    }
    else if (filename.endswith(".gif"))
    {
        response.setheader("content-type", "image/gif");
    }
    else if (filename.endswith(".pdf"))
    {
        response.setheader("content-type", "application/pdf");
    }
    else if (filename.endswith(".txt"))
    {
        response.setheader("content-type", qprintable("text/plain; charset="+encoding));
    }
    else if (filename.endswith(".html") || filename.endswith(".htm"))
    {
        response.setheader("content-type", qprintable("text/html; charset="+encoding));
    }
    else if (filename.endswith(".css"))
    {
        response.setheader("content-type", "text/css");
    }
    else if (filename.endswith(".js"))
    {
        response.setheader("content-type", "text/javascript");
    }
    else if (filename.endswith(".svg"))
    {
        response.setheader("content-type", "image/svg+xml");
    }
    else if (filename.endswith(".woff"))
    {
        response.setheader("content-type", "font/woff");
    }
    else if (filename.endswith(".woff2"))
    {
        response.setheader("content-type", "font/woff2");
    }
    else if (filename.endswith(".ttf"))
    {
        response.setheader("content-type", "application/x-font-ttf");
    }
    else if (filename.endswith(".eot"))
    {
        response.setheader("content-type", "application/vnd.ms-fontobject");
    }
    else if (filename.endswith(".otf"))
    {
        response.setheader("content-type", "application/font-otf");
    }
    else if (filename.endswith(".json"))
    {
        response.setheader("content-type", "application/json");
    }
    else if (filename.endswith(".xml"))
    {
        response.setheader("content-type", "text/xml");
    }
    // todo: add all of your content types
    else
    {
        qdebug("staticfilecontroller: unknown mime type for filename '%s'", qprintable(filename));
    }
}

c、下载的源码中有官方的例程可供参考

以上就是详解qt如何使用qtwebapp搭建http服务器的详细内容,更多关于qt qtwebapp搭建http服务器的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com