File: one_time_request.cc

package info (click to toggle)
cpp-httplib 0.18.7-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 2,500 kB
  • sloc: cpp: 15,918; makefile: 119; python: 50; sh: 32
file content (56 lines) | stat: -rw-r--r-- 1,331 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <httplib.h>
#include <iostream>

using namespace httplib;

const char *HOST = "localhost";
const int PORT = 1234;

void one_time_request_server(const char *label) {
  std::thread th;
  Server svr;

  svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
    res.set_content(std::string("Hello from ") + label, "text/plain");

    // Stop server
    th = std::thread([&]() { svr.stop(); });
  });

  svr.listen(HOST, PORT);
  th.join();

  std::cout << label << " ended..." << std::endl;
}

void send_request(const char *label) {
  Client cli(HOST, PORT);

  std::cout << "Send " << label << " request" << std::endl;
  auto res = cli.Get("/hi");

  if (res) {
    std::cout << res->body << std::endl;
  } else {
    std::cout << "Request error: " + to_string(res.error()) << std::endl;
  }
}

int main(void) {
  auto th1 = std::thread([&]() { one_time_request_server("Server #1"); });
  auto th2 = std::thread([&]() { one_time_request_server("Server #2"); });

  std::this_thread::sleep_for(std::chrono::milliseconds(100));

  send_request("1st");
  std::this_thread::sleep_for(std::chrono::milliseconds(100));

  send_request("2nd");
  std::this_thread::sleep_for(std::chrono::milliseconds(100));

  send_request("3rd");
  std::this_thread::sleep_for(std::chrono::milliseconds(100));

  th1.join();
  th2.join();
}