C++简单实现http服务端客户端传输实例

使用本代码有两个注意事项:

  1. 代码使用到了httplib库,需要下载然后把.h文件放到自己的目录下
    httplib下载地址:https://gitcode.net/mirrors/yhirose/cpp-httplib?utm_source=csdn_github_accelerator
  2. 使用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

猜你喜欢

转载自blog.csdn.net/gls_nuaa/article/details/130448032