c++ - 带有 cpprest 的多个 POST 请求,没有多线程和服务器停止
问题描述
当我发送多个帖子时,我的服务器 cpprest 出现了一些问题。
这是 MyServer 的代码:
MyServer::MyServer(utility::string_t url) : m_listener(url)
{
std::function<void(http_request)> fnPost = &MyServer::handle_post;
m_listener.support(methods::POST, fnPost);
mongocxx::instance instance{};
}
void MyServer::handle_error(pplx::task<void> &t)
{
try
{
t.get();
}
catch (...)
{
// Ignore the error, Log it if a logger is available
}
}
pplx::task<void> MyServer::open()
{
return m_listener.open().then([](pplx::task<void> t)
{ handle_error(t); });
}
pplx::task<void> MyServer::close()
{
return m_listener.close().then([](pplx::task<void> t)
{ handle_error(t); });
}
void MyServer::handle_post(http_request message)
{
message.extract_string().then([=](const utility::string_t &data)
{
try
{
message.reply(status_codes::Accepted);
DoSomething::doSomething(jsonObj, message);
catch (...)
{
message.reply(status_codes::InternalError).then([](pplx::task<void> t)
{ handle_error(t); });
}
}).then([](pplx::task<void> t){ handle_error(t); });
};
这是我的 DoSomething :
void DoSomething::doSomething(nlohmann::json jsonObj, http_request message)
{
try
{
(... do something with jsonObj)
message.reply(status_codes::OK).then([](pplx::task<void> t)
{ MyServer::handle_error(t); });
}
catch (const filesystem_error &ex)
{
message.reply(status_codes::InternalError).then([](pplx::task<void> t)
{ MyServer::handle_error(t); });
}
}
而我的主要:
int main(int argc, char ** argv) {
InterruptHandler * itrpt = new InterruptHandler();
itrpt -> hookSIGINT();
std::unique_ptr < MyServer > g_http;
utility::string_t adress = U("http://0.0.0.0:33333");
uri_builder uri(adress);
uri.append_path(U("MyServer/Action/"));
auto addr = uri.to_uri().to_string();
g_http = std::unique_ptr < MyServer > (new MyServer(addr));
try {
g_http -> open().wait();
ucout << utility::string_t(U("Listening for requests at: ")) << addr << std::endl;
InterruptHandler::waitForUserInterrupt();
} catch (const std::exception & e) {
printf("Error exception:%s\n", e.what());
}
return 0;
}
如果我在 doSomething 仍在运行时发起请求,则没有队列并且服务器正在停止。我不知道如何对我的服务器进行多线程处理以同时处理多个发布请求。我不是 C++ 专家,但我必须让自己适应这种语言才能完成我的工作。
我查看我的代码示例:https ://github.com/microsoft/cpprestsdk/blob/master/Release/samples/CasaLens/
解决方案
推荐阅读
- python - Django mixins.py 和 super() 函数
- c++ - 关于 cin 和输入缓冲区的简短问题
- javascript - 错误:无效的挂钩调用。Hooks 只能在 React Native 中的函数组件内部调用
- javascript - 谷歌表格脚本“超过最大执行时间”
- node.js - Firestore .get() 不会获取最新数据,而是获取旧版本的数据
- python - Python scikit-learn(发现偏差)
- vba - 将 PDF 表单保存到路径
- kotlin - 扩展 Kotlin 的 js 包装类
- python - repl.it 不和谐机器人中的位置参数错误
- mongodb - MongoDB:查找与正则表达式条件匹配的所有子文档