0

我使用 cpprestsdk 编写了一个简单的代码。我使用 map ( records) 作为 CommandHandler 类的成员,并在公共方法 ( has_record()) 中对其进行操作。

它在handler.open().wait()运行之前工作,但是当我在请求中调用它时,它崩溃了!

这是我的代码:

#define BOOST_DATE_TIME_NO_LIB

#include <string>
#include <vector>
#include <cpprest/uri.h>
#include <cpprest/http_listener.h>
#include <cpprest/asyncrt_utils.h>

using namespace std;
using namespace web;
using namespace http;
using namespace utility;
using namespace http::experimental::listener;

class CommandHandler
{
public:
    CommandHandler(utility::string_t url);
    pplx::task<void> open() { return m_listener.open(); }
    pplx::task<void> close() { return m_listener.close(); }
    bool has_record();

private:
    std::map< std::string, unsigned int > records;
    void handle_get_or_post(http_request message);
    http_listener m_listener;
};
bool CommandHandler::has_record()
{
    return records.size() > 0 && records.find("1") != records.end();
}

CommandHandler::CommandHandler(utility::string_t url) : m_listener(url)
{
    m_listener.support(methods::GET, std::bind(&CommandHandler::handle_get_or_post, this, std::placeholders::_1));
    m_listener.support(methods::POST, std::bind(&CommandHandler::handle_get_or_post, this, std::placeholders::_1));
}

void CommandHandler::handle_get_or_post(http_request request)
{
    if(this->has_record())
        request.reply(status_codes::OK, 1);
    else
        request.reply(status_codes::OK, 0);
};


int main(int argc, char** argv)
{
    try
    {
        utility::string_t address = U("http://127.0.0.1:9595");
        uri_builder uri(address);
        auto addr = uri.to_uri().to_string();

        CommandHandler handler(addr);
        if(handler.has_record())
            std::cout<<"work!";
        handler.open().wait();

        ucout << utility::string_t(U("Listening for requests at: ")) << addr << std::endl;
        ucout << U("Press ENTER key to quit...") << std::endl;
        std::string line;
        std::getline(std::cin, line);

        handler.close().wait();
    }
    catch (std::exception& ex)
    {
        ucout << U("Exception: ") << ex.what() << std::endl;
        ucout << U("Press ENTER key to quit...") << std::endl;
        std::string line;
        std::getline(std::cin, line);
    }

    return 0;
}
4

1 回答 1

0

我发现了问题,但我不明白它为什么会抛出。问题出在这行代码中:

request.reply(status_codes::OK, 0);

0会引发异常

于 2017-01-19T21:56:29.703 回答