From 0b541ffebc504fbace15ed930825085686b6d9b0 Mon Sep 17 00:00:00 2001 From: Rockybilly Date: Sun, 31 Jul 2022 15:27:38 +0300 Subject: [PATCH] =?UTF-8?q?Add=20get=5Fsocket=5Ffd=20method=20to=20Client?= =?UTF-8?q?=20and=20ClientImpl,=20add=20according=20unit=E2=80=A6=20(#1341?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add get_socket_fd method to Client and ClientImpl, add according unit test * Change name get_socket_fd to get_socket * Change name get_socket to socket Co-authored-by: ata.yardimci --- httplib.h | 10 ++++++++++ test/test.cc | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/httplib.h b/httplib.h index 94ec8a2..2a3742b 100644 --- a/httplib.h +++ b/httplib.h @@ -992,6 +992,8 @@ public: size_t is_socket_open() const; + socket_t socket() const; + void stop(); void set_hostname_addr_map(std::map addr_map); @@ -1344,6 +1346,8 @@ public: size_t is_socket_open() const; + socket_t socket() const; + void stop(); void set_hostname_addr_map(std::map addr_map); @@ -6944,6 +6948,10 @@ inline size_t ClientImpl::is_socket_open() const { return socket_.is_open(); } +inline socket_t ClientImpl::socket() const { + return socket_.sock; +} + inline void ClientImpl::stop() { std::lock_guard guard(socket_mutex_); @@ -8151,6 +8159,8 @@ inline Result Client::send(const Request &req) { return cli_->send(req); } inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); } +inline socket_t Client::socket() const { return cli_->socket(); } + inline void Client::stop() { cli_->stop(); } inline void diff --git a/test/test.cc b/test/test.cc index 264cd83..b8b8c35 100644 --- a/test/test.cc +++ b/test/test.cc @@ -4750,6 +4750,43 @@ TEST(SendAPI, SimpleInterface_Online) { EXPECT_EQ(301, res->status); } +TEST(ClientImplMethods, GetSocketTest) { + httplib::Server svr; + svr.Get( "/", [&](const httplib::Request& req, httplib::Response& res) { + res.status = 200; + }); + + auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); }); + + while (!svr.is_running()) { + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + + { + httplib::Client cli("http://127.0.0.1:3333"); + cli.set_keep_alive(true); + + // Use the behavior of cpp-httplib of opening the connection + // only when the first request happens. If that changes, + // this test would be obsolete. + + EXPECT_EQ(cli.socket(), INVALID_SOCKET); + + // This also implicitly tests the server. But other tests would fail much + // earlier than this one to be considered. + + auto res = cli.Get("/"); + ASSERT_TRUE(res); + + EXPECT_EQ(200, res->status); + ASSERT_TRUE(cli.socket() != INVALID_SOCKET); + } + + svr.stop(); + thread.join(); + ASSERT_FALSE(svr.is_running()); +} + // Disabled due to out-of-memory problem on GitHub Actions #ifdef _WIN64 TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {