Skip to content

Commit c7d22e4

Browse files
committed
Fixed timeout calculation bugs
1 parent 42f9f91 commit c7d22e4

File tree

1 file changed

+7
-13
lines changed

1 file changed

+7
-13
lines changed

httplib.h

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1701,7 +1701,7 @@ inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
17011701
pfd_read.fd = sock;
17021702
pfd_read.events = POLLIN;
17031703

1704-
auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
1704+
auto timeout = static_cast<int>(sec * 1000 + usec);
17051705

17061706
return handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); });
17071707
#else
@@ -1749,7 +1749,7 @@ inline bool wait_until_socket_is_ready(socket_t sock, time_t sec, time_t usec) {
17491749
pfd_read.fd = sock;
17501750
pfd_read.events = POLLIN | POLLOUT;
17511751

1752-
auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
1752+
auto timeout = static_cast<int>(sec * 1000 + usec);
17531753

17541754
auto poll_res = handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); });
17551755

@@ -1850,25 +1850,19 @@ class BufferStream : public Stream {
18501850
size_t position = 0;
18511851
};
18521852

1853-
inline bool keep_alive(socket_t sock, std::function<bool()> is_shutting_down) {
1853+
inline bool keep_alive(socket_t sock) {
18541854
using namespace std::chrono;
18551855
auto start = steady_clock::now();
18561856
while (true) {
18571857
auto val = select_read(sock, 0, 10000);
1858-
if (is_shutting_down && is_shutting_down()) {
1859-
return false;
1860-
} else if (val < 0) {
1858+
if (val < 0) {
18611859
return false;
18621860
} else if (val == 0) {
18631861
auto current = steady_clock::now();
1864-
auto sec = duration_cast<seconds>(current - start);
1865-
if (sec.count() > CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND) {
1862+
auto duration = duration_cast<milliseconds>(current - start);
1863+
auto timeout = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND * 100 + CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
1864+
if (duration.count() > timeout) {
18661865
return false;
1867-
} else if (sec.count() == CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND) {
1868-
auto usec = duration_cast<nanoseconds>(current - start);
1869-
if (usec.count() > CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND) {
1870-
return false;
1871-
}
18721866
}
18731867
std::this_thread::sleep_for(std::chrono::milliseconds(1));
18741868
} else {

0 commit comments

Comments
 (0)