使用本代码有两个注意事项:
- 代码使用到了httplib库,需要下载然后把.h文件放到自己的目录下
httplib下载地址:https://gitcode.net/mirrors/yhirose/cpp-httplib?utm_source=csdn_github_accelerator - 使用g++进行编译的时候要加上-lpthread参数才能正确编译成功
服务端代码:
#include <iostream>
#include <chrono>
#include <cstdio>
#include "httplib.h"
using namespace httplib;
int main()
{
Server svr;
if (!svr.is_valid())
{
printf("server has an error...\n");
return -1;
}
svr.Get("/hi", [](const Request& , Response& res)
{
res.set_content("Hello http!\n", "text/plain");
});
svr.Get("/stop",
[&](const Request& , Response& ) { svr.stop(); });
svr.listen("localhost", 1234);
}
客户端代码:
#include <iostream>
#include "httplib.h"
#include <iostream>
using namespace std;
int main()
{
httplib::Client cli("localhost", 1234);
if (auto res = cli.Get("/hi"))
{
cout << res->status << endl;
cout << res->get_header_value("Content-Type") << endl;
cout << res->body << endl;
}
else
{
}
return 0;
}
关于传输数据,本例中服务端只使用了“Hello http!”来代替,可以换成string类型的数据用于传输JSON等格式数据
参考:https://blog.51cto.com/u_10486491/3215390
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)