How can I keep the server running without using std::getline or boost::asio ?
Does cpprest provide any interfaces for this?

Using boost::asio can achieve this, but does cpprest provide any other useful method? If so, the advantages compared to using boost::asio directly?

Here is my code:

int main(int argc, char* argv[]) { utility::string_t port = U("8080"); utility::string_t address = U("http://localhost:"); address.append(port); // init server uri_builder uri(address); uri.append_path(U("/api/predict/")).append(U("model")); auto addr = uri.to_uri().to_string(); http_listener m_listener(addr); m_listener.support(methods::GET, std::bind(&handle_get, std::placeholders::_1)); m_listener.support(methods::POST, std::bind(&handle_post, std::placeholders::_1)); m_listener.open().wait(); std::cout << utility::string_t(U("Listening for requests at: ")) << addr << std::endl; boost::asio::io_context handler_context; boost::asio::signal_set signals(handler_context, SIGINT ); signals.async_wait( [&](boost::system::error_code, int signum) { handler_context.stop(); }); handler_context.run(); // std::cout << "Press ENTER to exit." << std::endl; // std::string line; // std::getline(std::cin, line); m_listener.close().wait(); return 0; }

wohlstad's user avatar

wohlstad

36.8k18 gold badges79 silver badges113 bronze badges

Ypro's user avatar

Assuming your server runs as a console process. I kind of have a windows only example at the moment (but I am sure something like this exists for Linux too) You can use a signal handler that for example waits for a CTRL+break, or closing the terminal window (if any).
So my main point is that you can also look in your OS API for something that helps you wait.

bool s_shutdownRequested = false; std::mutex s_mtx; std::condition_variable s_cv; inline BOOL WINAPI ConsoleHandlerRoutine(DWORD dwCtrlType) { switch (dwCtrlType) { case CTRL_C_EVENT: case CTRL_CLOSE_EVENT: case CTRL_BREAK_EVENT: case CTRL_LOGOFF_EVENT: case CTRL_SHUTDOWN_EVENT: { std::scoped_lock lock{s_mtx}; s_shutdownRequested = true; s_cv.notify_all(); return TRUE; } default: return FALSE; } } } // namespace inline void WaitForShutdown() { s_shutdownRequested = false; SetConsoleCtrlHandler(ConsoleHandlerRoutine, TRUE); std::unique_lock lock{s_mtx}; s_cv.wait(lock, [] { return s_shutdownRequested; }); SetConsoleCtrlHandler(ConsoleHandlerRoutine, FALSE); }

And then you can call WaitForShutDown just before return in your main.
This also means you can handle server shutdown gracefully, since this allows you to put cleanup/shutdown code after WaitForShutDown (which still gets executed before the process really stops)

Pepijn Kramer's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.