1.安装Tufao
注意:Tufao是基于Qt的通信库,所以必须确保已经安装了Qt,配置好环境变量; 关于Qt版本要求在Tufao的github上有描述,这里实用的是Qt5.7;
可能需要先sudo apt-get install cmake qtsdk
在Github上查找tufao,点击release,下载1.4.0版本的代码(因为1.4.1版本cmake过程中提示:用到的boost/http/...目录,实际安装boost库编译安装 之后没有那个文件夹。。。百度不得其解,所以 只有);在代码解压的目录,新建build文件夹,进入build目录中执行编译命令 cmake .. -DCMAKE_INSTALL_PREFIX=/usr ;然后 make install 即可。
2.Tufao的使用
新建 Empty Qt Project 并创建无窗口程序
main.cpp如下:
#include<QCoreApplication> //用于在创建无窗口程序时替代QApplication
#include "MyServer.h" //新添加的类继承于QObject
int main(int argc,char*argv[])
{
QCoreApplication app(argc,argv);
Myserver* s = new MyServer;
app.exec();
}
test.pro文件如下:
HEADERS += MyServer.h
SOURCES += MyServer.cpp main.cpp
CONFIG +=Tufao1 C++11 //为了实现Web服务器,需要为 CONFIG 添加 Tufao1 ,这个配置文件会自动将Tufao相关的库导入到工程。
MyServer.h内容
#ifndef MYSERVER_H
#define MYSERVER_H
#include <QObject>
#include <Tufao/HttpServer>
#include <Tufao/HttpServerRequest>
#include <Tufao/HttpServerResponse>
using namespace Tufao;
class MyServer : public QObject
{
Q_OBJECT
public:
explicit MyServer(QObject *parent = 0);
HttpServer * server;
signals:
public slots:
void slotRequestReady(Tufao::HttpServerRequest&,Tufao::HttpServerResponse&);
};
#endif // MYSERVER_H
#include "MyServer.h"
MyServer::MyServer(QObject *parent) :QObject(parent)
{
server = new HttpServer;
if(server->listen(QHostAddress::Any,8080)) //Http通信过程,server端只需要listen即可
{
qDebug()<<"listen at 8080 OK";
}
else
{
qDebug()<<"listen error at 8080";
}
//connect(server,SIGNAL(requestReady(Tufao::HttpServerRequest&,Tufao::HttpServerResponse&)),
// this,SLOT(slotRequestReady(Tufao::HttpServerRequest&,Tufao::HttpServerResponse&)));
//推荐使用connect函数的下面的写法,因为直接给出了函数地址,执行效率更高,函数参数省略了,修改更快;缺点是要是有槽函数重载时不能使用这种方式。
connect(server,&HttpServer::requestReady,this,&MyServer::slotRequestReady);
}
void MyServer::slotRequestReady(HttpServerRequest&req,HttpServerResponse&res)
{
res.writeHead(HttpResponseStatus::OK); //Http通信规定,首先要发一个执行结果。
res.write("hello world\n");
res.write("body of comunication\n"); //可以有很多个write,但是必须最后以 end 结束。猜想需要通过end确定报文的长度。
res.end("this is the end of this message\n");
}
运行成功之后,在LINUX terminal 命令行下面使用curl测试;
执行 curl 127.0.0.1:8080
返回的报文直接打印。