Skip to content

Commit ccc81d8

Browse files
committed
Add socket timeout config(ClickHouse#141)
1 parent 3e1d5c7 commit ccc81d8

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

clickhouse/base/socket.cpp

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ NetworkAddress::NetworkAddress(const std::string& host, const std::string& port)
183183
hints.ai_socktype = SOCK_STREAM;
184184
// using AI_ADDRCONFIG on windows will cause getaddrinfo to return WSAHOST_NOT_FOUND
185185
// for more information, see https://github.com/ClickHouse/clickhouse-cpp/issues/195
186-
#if defined(_unix_)
186+
#if defined(_unix_)
187187
if (!Singleton<LocalNames>()->IsLocalName(host)) {
188188
// https://linux.die.net/man/3/getaddrinfo
189189
// If hints.ai_flags includes the AI_ADDRCONFIG flag,
@@ -292,6 +292,17 @@ void Socket::SetTcpNoDelay(bool nodelay) noexcept {
292292
#endif
293293
}
294294

295+
void Socket::SetSocketTimeoutTime(unsigned int time) noexcept {
296+
struct timeval time_val = {time, 0};
297+
#if defined(_unix_) && defined(_linux_)
298+
setsockopt(handle_, SOL_SOCKET, SO_RCVTIMEO, (const char*)&time_val, sizeof time_val);
299+
#elif defined(_darwin_)
300+
setsockopt(handle_, SOL_SOCKET, SO_RCVTIMEO, (const char*)&time_val, sizeof time_val);
301+
#elif defined(_unix_)
302+
// setsockopt not support SO_RCVTIMEO in BSD.
303+
#endif
304+
}
305+
295306
std::unique_ptr<InputStream> Socket::makeInputStream() const {
296307
return std::make_unique<SocketInput>(handle_);
297308
}
@@ -325,6 +336,9 @@ void NonSecureSocketFactory::setSocketOptions(Socket &socket, const ClientOption
325336
if (opts.tcp_nodelay) {
326337
socket.SetTcpNoDelay(opts.tcp_nodelay);
327338
}
339+
if (opts.socket_timeout_sec) {
340+
socket.SetSocketTimeoutTime(opts_.socket_timeout_sec);
341+
}
328342
}
329343

330344
SocketInput::SocketInput(SOCKET s)

clickhouse/base/socket.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,9 @@ class Socket : public SocketBase {
100100
/// @params nodelay whether to enable TCP_NODELAY
101101
void SetTcpNoDelay(bool nodelay) noexcept;
102102

103+
/// @params time the time (in seconds) the socket recv timeout.
104+
void SetSocketTimeoutTime(unsigned int time) noexcept;
105+
103106
std::unique_ptr<InputStream> makeInputStream() const override;
104107
std::unique_ptr<OutputStream> makeOutputStream() const override;
105108

0 commit comments

Comments
 (0)