最近在划水時接觸到一個非常強大的開源C++異步網絡庫workflow以及其一種實現框架wfrest
原帖鏈接:
workflow: https://www.zhihu.com/question/41609070/answer/2073049547
wfrest: https://www.zhihu.com/people/liyingxin1412
作者工作時主要使用的java語言,然而也偶爾需要用到c++,也是第一次接觸到c++的網絡服務器,這也可以作為一種C++/Java之間的RPC通信方式,因此進行了簡單了解。
安裝
安裝環境:ubuntu20.04
首先需要前往Git下載workflow與wfrest
workflow: https://github.com/sogou/workflow
wfrest: https://github.com/wfrest/wfrest
使用Git clone命令下載到本地,按照項目中的readme文檔install項目
安裝成功后,可以在/usr/local文件夾中看到libwfrest.a libworkflow.a libworkflow.so 其中.a .so分別為靜態庫與動態庫文件(有其中的一個就可以使用,只是二者有區別,會影響項目文件的大小)
使用
創建一個新的C++項目
在CMakeList文件中鏈接庫wfrest workflow ssl crypto pthread z
target_link_libraries(webserver wfrest workflow ssl crypto pthread z)
如果不使用cmake工具,則需要在編譯時手動鏈接這些庫
編譯成功后,即可啟動一個服務,附作者的demo
#include "wfrest/HttpServer.h"
using namespace wfrest;
int main()
{
HttpServer svr;
// curl -v http://ip:port/hello
svr.GET("/hello", [](const HttpReq *req, HttpResp *resp)
{
resp->String("world\n");
});
// curl -v http://ip:port/data
svr.GET("/data", [](const HttpReq *req, HttpResp *resp)
{
std::string str = "Hello world";
resp->String(std::move(str));
});
// curl -v http://ip:port/post -d 'post hello world'
svr.POST("/post", [](const HttpReq *req, HttpResp *resp)
{
// reference, no copy here
std::string& body = req->body();
fprintf(stderr, "post data : %s\n", body.c_str());
});
if (svr.start(8888) == 0)
{
getchar();
svr.stop();
} else
{
fprintf(stderr, "Cannot start server");
exit(1);
}
return 0;
}
