[C/C++][인터넷] [C++] Full-fledged client-server example with C++ REST SDK 2.10

Full-fledged client-server example with C++ REST SDK 2.10

 

Four years ago I wrote a blog post that shown how to build a web server using the http_listener from the C++ REST SDK library as well as a client application that consumed the exposed resources. Over the years there have been various changes to the API from the library and some readers complained the code no longer compiled. Eventually, I decided to revisit that post and update my code to the latest version of the library, which at this time is 2.10.

I will not reiterate all the details described in the former article. However, in summary, the server maintains a dictionary of values (both keys and values are strings). Through HTTP calls a client can retrieve the content of the dictionary, add new values, update or delete existing ones.

HTTP method Description Request Response
GET retrieves all the key-value pair from the dictionary   {"one" : "100", "two" : "200"}
POST retrieves the values of the specified keys from the dictionary ["one", "two", "three"] {"one" : "100", "three" : "", "two" : "200"}
PUT inserts new pairs of key-values in the dictionary; if a key is already found its value is updated {"one" : "100", "two" : "200"} {"one" : "", "two" : ""}
DELETE deletes the specified keys from the dictionary ["one"] {"one" : ""}

Here is the server code:

#include <cpprest/http_listener.h>
#include <cpprest/json.h>
#pragma comment(lib, "cpprest_2_10")

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

#include <iostream>
#include <map>
#include <set>
#include <string>
using namespace std;

#define TRACE(msg)            wcout << msg
#define TRACE_ACTION(a, k, v) wcout << a << L" (" << k << L", " << v << L")\n"

map<utility::string_t, utility::string_t> dictionary;

void display_json(
   json::value const & jvalue,
   utility::string_t const & prefix)
{
   wcout << prefix << jvalue.serialize() << endl;
}

void handle_get(http_request request)
{
   TRACE(L"\nhandle GET\n");

   auto answer = json::value::object();

   for (auto const & p : dictionary)
   {
      answer[p.first] = json::value::string(p.second);
   }

   display_json(json::value::null(), L"R: ");
   display_json(answer, L"S: ");

   request.reply(status_codes::OK, answer);
}

void handle_request(
   http_request request,
   function<void(json::value const &, json::value &)> action)
{
   auto answer = json::value::object();

   request
      .extract_json()
      .then([&answer, &action](pplx::task<json::value> task) {
         try
         {
            auto const & jvalue = task.get();
            display_json(jvalue, L"R: ");

            if (!jvalue.is_null())
            {
               action(jvalue, answer);
            }
         }
         catch (http_exception const & e)
         {
            wcout << e.what() << endl;
         }
      })
      .wait();

   
   display_json(answer, L"S: ");

   request.reply(status_codes::OK, answer);
}

void handle_post(http_request request)
{
   TRACE("\nhandle POST\n");

   handle_request(
      request,
      [](json::value const & jvalue, json::value & answer)
   {
      for (auto const & e : jvalue.as_array())
      {
         if (e.is_string())
         {
            auto key = e.as_string();
            auto pos = dictionary.find(key);

            if (pos == dictionary.end())
            {
               answer[key] = json::value::string(L"<nil>");
            }
            else
            {
               answer[pos->first] = json::value::string(pos->second);
            }
         }
      }
   });
}

void handle_put(http_request request)
{
   TRACE("\nhandle PUT\n");

   handle_request(
      request,
      [](json::value const & jvalue, json::value & answer)
   {
      for (auto const & e : jvalue.as_object())
      {
         if (e.second.is_string())
         {
            auto key = e.first;
            auto value = e.second.as_string();

            if (dictionary.find(key) == dictionary.end())
            {
               TRACE_ACTION(L"added", key, value);
               answer[key] = json::value::string(L"<put>");
            }
            else
            {
               TRACE_ACTION(L"updated", key, value);
               answer[key] = json::value::string(L"<updated>");
            }

            dictionary[key] = value;
         }
      }
   });
}

void handle_del(http_request request)
{
   TRACE("\nhandle DEL\n");

   handle_request(
      request,
      [](json::value const & jvalue, json::value & answer)
   {
      set<utility::string_t> keys;
      for (auto const & e : jvalue.as_array())
      {
         if (e.is_string())
         {
            auto key = e.as_string();

            auto pos = dictionary.find(key);
            if (pos == dictionary.end())
            {
               answer[key] = json::value::string(L"<failed>");
            }
            else
            {
               TRACE_ACTION(L"deleted", pos->first, pos->second);
               answer[key] = json::value::string(L"<deleted>");
               keys.insert(key);
            }
         }
      }

      for (auto const & key : keys)
         dictionary.erase(key);
   });
}

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

   listener.support(methods::GET,  handle_get);
   listener.support(methods::POST, handle_post);
   listener.support(methods::PUT,  handle_put);
   listener.support(methods::DEL,  handle_del);

   try
   {
      listener
         .open()
         .then([&listener]() {TRACE(L"\nstarting to listen\n"); })
         .wait();

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

   return 0;
}

And this is the client code:

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

#include <cpprest/http_client.h>
#include <cpprest/json.h>
#pragma comment(lib, "cpprest_2_10")

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

#include <iostream>
using namespace std;

void display_json(
   json::value const & jvalue, 
   utility::string_t const & prefix)
{
   wcout << prefix << jvalue.serialize() << endl;
}

pplx::task<http_response> make_task_request(
   http_client & client,
   method mtd,
   json::value const & jvalue)
{
   return (mtd == methods::GET || mtd == methods::HEAD) ?
      client.request(mtd, L"/restdemo") :
      client.request(mtd, L"/restdemo", jvalue);
}

void make_request(
   http_client & client, 
   method mtd, 
   json::value const & jvalue)
{
   make_task_request(client, mtd, jvalue)
      .then([](http_response response)
      {
         if (response.status_code() == status_codes::OK)
         {
            return response.extract_json();
         }
         return pplx::task_from_result(json::value());
      })
      .then([](pplx::task<json::value> previousTask)
      {
         try
         {
            display_json(previousTask.get(), L"R: ");
         }
         catch (http_exception const & e)
         {
            wcout << e.what() << endl;
         }
      })
      .wait();
}

int main()
{
   http_client client(U("http://localhost"));

   auto putvalue = json::value::object();
   putvalue[L"one"] = json::value::string(L"100");
   putvalue[L"two"] = json::value::string(L"200");

   wcout << L"\nPUT (add values)\n";
   display_json(putvalue, L"S: ");
   make_request(client, methods::PUT, putvalue);

   auto getvalue = json::value::array();
   getvalue[0] = json::value::string(L"one");
   getvalue[1] = json::value::string(L"two");
   getvalue[2] = json::value::string(L"three");

   wcout << L"\nPOST (get some values)\n";
   display_json(getvalue, L"S: ");
   make_request(client, methods::POST, getvalue);

   auto delvalue = json::value::array();
   delvalue[0] = json::value::string(L"one");

   wcout << L"\nDELETE (delete values)\n";
   display_json(delvalue, L"S: ");
   make_request(client, methods::DEL, delvalue);

   wcout << L"\nPOST (get some values)\n";
   display_json(getvalue, L"S: ");
   make_request(client, methods::POST, getvalue);

   auto nullvalue = json::value::null();

   wcout << L"\nGET (get all values)\n";
   display_json(nullvalue, L"S: ");
   make_request(client, methods::GET, nullvalue);

   return 0;
}

Notice there are slight changes in the way output is formatted, both in the server and the client application. The rest is mostly unchanged, except for the handling of JSON, that has changed significatly since version 1.1. Again, please see the original post for an explanation of the code.

The output from running these client and server applications is shown below. On the left is the client output, and on the right the server output.

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
78 [linux master][리눅스 마스터][국가기술자격] 리눅스 기초 명령어 : 도움말 보기 -man, info, help file 졸리운_곰 2025.02.18 215
77 [linux master][리눅스 마스터][국가기술자격] 우분투에서 NTFS 를 Read/Write로 마운트 (듀얼 부팅 화일 공유) file 졸리운_곰 2024.12.22 277
76 [linux master] 커맨드 라인에서 display 문제로 gui 프로그램이 열리지 않을 때, 졸리운_곰 2024.12.22 338
75 [linux master][리눅스 마스터][국가기술자격] VirtualBox ubuntu ↔ 윈도우 공유 폴더 설정 file 졸리운_곰 2024.12.20 293
74 [linux master][리눅스 마스터][국가기술자격] How to fix sudo after "chmod -R 777 /usr/bin"? /usr/bin/sudo must be owned by uid 0 and have the setuid bit set 졸리운_곰 2024.09.23 754
73 [linux master][리눅스 마스터][국가기술자격] [리눅스/find] 파일찾기 - 허가 거부 제외하고 결과물 출력하기 file 졸리운_곰 2024.07.21 326
72 [linux master][리눅스 마스터][국가기술자격] [리눅스] socat 명령어(proxy) file 졸리운_곰 2024.02.28 343
71 [linux master][리눅스 마스터][국가기술자격] [리눅스] Linux nc 명령어는 무엇이고 어떻게 쓰는 가? 졸리운_곰 2024.02.28 345
70 [linux master][리눅스 마스터][국가기술자격] [리눅스] AWK 명령어 사용법과 여러가지 실용적인 예제 모음 file 졸리운_곰 2024.02.02 300
69 [linux master][리눅스 마스터][국가기술자격] [vi 명령어] vi 명령어 정리 file 졸리운_곰 2024.02.02 283
68 [linux telnet(ssh) 창에서 MSDOS emulation 에뮬레이션 Install dosemu2 dos emulator in Ubuntu and Ubuntu based distributions file 졸리운_곰 2024.01.05 289
67 [linux master][리눅스 마스터][국가기술자격] [Azure] Linux(ubuntu) 우분투 서버 GUI 환경으로 원격 접속하기 - feat. Ubuntu-desktop file 졸리운_곰 2023.11.22 334
66 [linux master][리눅스 마스터][국가기술자격] [Linux] vim(vi) editor 한글 입력시 깨짐 해결방법 file 졸리운_곰 2023.11.22 337
65 [리눅스][linux] 리눅스 서버 다운 원인 분석과 해결 (책) 방안 졸리운_곰 2023.10.03 234
64 [리눅스][linux] Ubuntu/Linux에서 user password를 짧거나 쉬운 password로 변경하는 방법. file 졸리운_곰 2023.01.08 331
63 [linux master][리눅스 마스터][국가기술자격] [GCP 원데이] 서버가 죽는 이유, Message Queue file 졸리운_곰 2023.01.01 220
62 [linux master][리눅스 마스터][국가기술자격] 리눅스 서버 다운 원인 5가지 졸리운_곰 2023.01.01 224
61 [linux master][리눅스 마스터][국가기술자격] Shell In A Box-원격 Linux 서버에 액세스하기위한 웹 기반 SSH 터미널 file 졸리운_곰 2022.11.17 266
60 [linux dev env] [우분투 서버] noVNC 접속 file 졸리운_곰 2022.11.16 338
59 [Linux WSL2] WSL2에서 Ubuntu GUI 프로그램 실행하기 (VcXsrv) file 졸리운_곰 2022.08.20 317
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED