yhirose/cpp-httplib

How to run 2 servers in same process?

engjq opened this issue · 1 comments

How to run 2 servers in same process?
like

std::thread([](){
    httplib::server server;
    server.listen("0.0.0.0",8080);
}).detach();

httplib::server server2;
server2.listen("0.0.0.0",8081);

The server listen on 8080 seems not working...

Here is the sample code.

#include <httplib.h>
#include <iostream>

using namespace httplib;

const auto HOST = "0.0.0.0";

const auto PORT = 1234;
const auto PORT2 = 1235;

int main(void) {
  Server svr;
  svr.Get("/hi", [](const Request & /*req*/, Response &res) {
    res.set_content("hi", "text/plain");
  });

  Server svr2;
  svr2.Get("/hi", [](const Request & /*req*/, Response &res) {
    res.set_content("hi2", "text/plain");
  });

  auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  auto thread2 = std::thread([&]() { svr2.listen(HOST, PORT2); });

  auto se = detail::scope_exit([&] {
    svr.stop();
    thread.join();
    svr2.stop();
    thread2.join();
  });

  svr.wait_until_ready();
  svr2.wait_until_ready();

  {
    Client cli(HOST, PORT);

    auto res = cli.Get("/hi");
    std::cout << res->body << std::endl;
  }

  {
    Client cli(HOST, PORT2);

    auto res = cli.Get("/hi");
    std::cout << res->body << std::endl;
  }
}

This is the result on my MacBook.

hi
hi2