cpprestsdk 客户端/服务器未返回 OK 状态

时间:2021-05-25 07:15:59

标签: cpprest-sdk

我参考了这个link

编写小型客户端和服务器代码

客户代码:

//g++ -o client client.cpp -lcpprest -lpthread -lcrypto -lboost_system
  #include <cpprest/http_client.h>

  using namespace web;
  using namespace web::http;
  using namespace web::http::client;

  #include <iostream>
  using namespace std;

  void make_request( http_client & client, method mtd )
  {
    client.request(mtd, "/restdemo").then([](http_response response)
        {
            cout << __LINE__<<" here in get request \n";
            if (response.status_code() == status_codes::OK)
            {
                cout << __LINE__<<" here in get request \n";
                cout << response.body();
            }
            else
            {
                cout << __LINE__<<" here in get request \n";
            }
            return pplx::task_from_result(json::value());
        }).then([](pplx::task<json::value> previousTask)
            {
            }).wait();
  }

  int main()
  {
      http_client client( "http://localhost" );
      make_request( client, methods::GET );
      return 0;
  }

服务器代码:

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

#include <iostream>
using namespace std;

void handle_get(http_request request)
{
    cout << __LINE__<<" here in get request \n";
    request.reply(status_codes::OK, "GET Method result ");
}

int main()
{
   http_listener listener("http://localhost/restdemo");

   listener.support(methods::GET,  handle_get);
   try
   {
      listener
         .open()
         .then([&listener]() { cout<<"\nstarting to listen\n"; })
         .wait();

      while (true);
   }
   catch (exception const & e)
   {
      cout << e.what() << endl;
   }

   return 0;
}

我看到服务器没有响应 get 方法。

  1. 有人可以帮助我做错的地方吗?
  2. 我无法理解 while(true) 的目的;有没有更好的编码方式,因为它可能会浪费 CPU?

0 个答案:

没有答案