问题
I know boost ASIO has a socket option to enable tcp keep-alive, but how can I set it to a specific value?
If not through Boost defined types, perhaps I can get the socket handle and set the option using posix setsocketopt() call?
回答1:
There are two parts to keep-alive. First, it can be enabled with default values. Second, keep alive interval and timeout can be set.
For the first part you can use this:
unsigned long val = 1;
int res = setsockopt(socket, SOL_SOCKET, SO_KEEPALIVE, (char*)&val, sizeof val);
Keep-alive parameters cannot be set in posix. However, on Windows it can be done as the following:
tcp_keepalive alive;
alive.onoff = TRUE;
alive.keepalivetime = 60000;
alive.keepaliveinterval = 1000;
int bytes_ret=0;
res = WSAIoctl(socket, SIO_KEEPALIVE_VALS, &alive, sizeof(alive), NULL, 0,
&bytes_ret, NULL, NULL);
Both on Windows and Linux you can define keep-alive timeout and interval system-wide.
来源:https://stackoverflow.com/questions/9085286/how-do-i-set-tcp-keep-alive-to-a-specific-value-using-boost-asio