c++future 配合httplib post 高级技巧

修正

这篇文章有修正

c++ future

c++11 的future函数实际上是线程的高级封装。
先看一个线程

void foo(int &n)
{
	for (int i = 0; i < 5; ++i) {
		std::cout << "Thread executing\n";
		++n;
		std::this_thread::sleep_for(std::chrono::milliseconds(10));
	}
}
int main()
{
	int n = 0;
	std::thread t1(foo,std::ref(n));
	std::thread::id t1_id = t1.get_id();


	std::cout << "t1's id: " << t1_id << '\n';

	t1.join();
	std::cout << "the n is " << n<<std::endl;
	getchar();
}

执行以后结果为:

Thread executing
t1’s id: 22864
Thread executing
Thread executing
Thread executing
Thread executing
the n is 5

使用std::future

ok,我们可以使用更为简单的方法来使用std::future,

int foo(int &n)
{
	for (int i = 0; i < 5; ++i) {
		std::cout << "Thread executing\n";
		++n;
		std::this_thread::sleep_for(std::chrono::milliseconds(10));
	}
	return n;
}
//int main()
//{
//	int n = 0;
//	std::thread t1(foo,std::ref(n));
//	std::thread::id t1_id = t1.get_id();
//
//
//	std::cout << "t1's id: " << t1_id << '\n';
//
//	t1.join();
//	std::cout << "the n is " << n<<std::endl;
//	getchar();
//}
int main()
{
	int n = 0;
	std::future<int> result = std::async(foo,std::ref(n));
	std::cout << result.get() << std::endl;
	getchar();
}

输出:
Thread executing
Thread executing
Thread executing
Thread executing
Thread executing
5

可以看到,我们使用

	std::future<int> result = std::async(foo,std::ref(n));
	std::cout << result.get() << std::endl;

这简短的两句话,就代替了所有的线程语句,看不到任何线程的启动和等待停止,result.get()会自动为我们阻塞等待结果。

httplib

httplib 是一个非常优秀的http协议封装,但成事在人,我们在使用的时候,如果一不小心就会发生:
1 socket阻塞
2 逻辑问题耗时
为了使得
例如以下这一段程序:

	httplib::Client client(v_param->end_call.c_str());

	const char *stret = "{\"type\":\"startLive\",\"ChapterId\":%d,"
		"\"CourseId\":%d,"
		"\"Url\":\"%s\","
		"\"TUrl\":\"%s\","
		"\"SUrl\":\"%s\",\"Statue\":0}";
	char buffer[1024];

	string s = v_param->surl.empty() ? "" : "student";
	string t = v_param->turl.empty() ? "" : "teacher";
	sprintf(buffer, stret, v_ChapterId, v_CourseId,
		v_param->addr_flv.c_str(), t.c_str(), s.c_str());

	//cout << buffer << endl;
	httplib::Headers header = {
		{ "token", v_token.c_str() }
	};
	auto res = client.Post("/api/v1/live_video_handle",
		header,
		buffer, strlen(buffer), "application/json");

	if (res.error() == httplib::Error::Success)
	{
		cout << res->body << endl;
	}
	//停止直播
	Stop_av(); //耗时等待
	return 0;

以上的代码有两个地方可能会产生问题:
1 Post 可能会遇到阻塞
2 stop_av 可能会遇到阻塞

一旦遇到这种情况,我们可能会考虑这种方式:启动一个线程去做,不过,我们可以更为简单,使用std::future,将以上代码封装在一个函数里面,函数名称为result_future。

std::async(std::bind(&classname::result_future,this));

一句话,就避免了线程的管理,是不是很方便呢。

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
以下是一个httplib post示例代码的C++版本: #include <iostream> #include <sstream> #include <string> #include <ctime> #include <cmath> #include <cstdlib> #include <cstdio> #include <cstring> #include <vector> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> std::string createRequestBody(const std::string& data) { std::ostringstream request; request << "POST /upload HTTP/1.1\r\n"; request << "Host: example.com\r\n"; request << "Content-Type: application/x-www-form-urlencoded\r\n"; request << "Content-Length: " << data.length() << "\r\n\r\n"; request << data; return request.str(); } int main() { int clientSocket = socket(AF_INET, SOCK_STREAM, 0); if (clientSocket == -1) { std::cout << "Failed to create socket." << std::endl; return 1; } // 连接到服务器 sockaddr_in serverAddress{}; serverAddress.sin_family = AF_INET; serverAddress.sin_port = htons(80); serverAddress.sin_addr.s_addr = inet_addr("127.0.0.1"); if (connect(clientSocket, reinterpret_cast<struct sockaddr*>(&serverAddress), sizeof(serverAddress)) != 0) { std::cout << "Failed to connect to the server." << std::endl; return 1; } // 准备请求体 std::string requestData = "key1=value1&key2=value2"; // 创建请求 std::string requestBody = createRequestBody(requestData); // 发送请求 if (send(clientSocket, requestBody.c_str(), requestBody.length(), 0) < 0) { std::cout << "Failed to send the request." << std::endl; } // 接收响应 char serverResponse[4096]; memset(serverResponse, 0, sizeof(serverResponse)); if (recv(clientSocket, serverResponse, sizeof(serverResponse), 0) < 0) { std::cout << "Failed to receive the server's response." << std::endl; } // 处理响应 std::cout << "Server Response: " << std::endl; std::cout << serverResponse << std::endl; // 关闭连接 close(clientSocket); return 0; } 以上代码实现了一个简单的httplib post请求的发送和接收响应过程。首先,它创建了一个套接字来进行与服务器的连接。然后,它构造了HTTP请求的请求体,并将其发送到服务器。之后,它接收来自服务器的响应,并将其打印到控制台上。最后,它关闭了套接字来终止与服务器的连接。在实际使用时,你需要根据实际情况修改服务器地址、端口以及请求体的内容。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qianbo_insist

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值