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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值