Recommended epoll/tcp options

This commit is contained in:
2025-08-19 12:27:03 -04:00
parent 499de3837a
commit addac1b0b7

View File

@@ -84,6 +84,13 @@ int getListenFd(const char *node, const char *service) {
continue; // Try next address continue; // Try next address
} }
// Enable TCP_NODELAY for low latency (disable Nagle's algorithm)
if (setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val)) == -1) {
perror("setsockopt TCP_NODELAY");
close(sfd);
continue; // Try next address
}
// Set socket to non-blocking for graceful shutdown // Set socket to non-blocking for graceful shutdown
int flags = fcntl(sfd, F_GETFL, 0); int flags = fcntl(sfd, F_GETFL, 0);
if (flags == -1) { if (flags == -1) {
@@ -482,9 +489,10 @@ int main(int argc, char *argv[]) {
abort(); abort();
} }
// Add listen socket to accept epoll // Add listen socket to accept epoll with EPOLLEXCLUSIVE for better load
// balancing
struct epoll_event listen_event; struct epoll_event listen_event;
listen_event.events = EPOLLIN; listen_event.events = EPOLLIN | EPOLLEXCLUSIVE;
listen_event.data.fd = sockfd; listen_event.data.fd = sockfd;
if (epoll_ctl(accept_epollfd, EPOLL_CTL_ADD, sockfd, &listen_event) == -1) { if (epoll_ctl(accept_epollfd, EPOLL_CTL_ADD, sockfd, &listen_event) == -1) {
perror("epoll_ctl listen socket"); perror("epoll_ctl listen socket");
@@ -545,6 +553,14 @@ int main(int argc, char *argv[]) {
continue; continue;
} }
// Enable keepalive to detect dead connections
int keepalive = 1;
if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &keepalive,
sizeof(keepalive)) == -1) {
perror("setsockopt SO_KEEPALIVE");
// Continue anyway - not critical
}
auto conn = std::make_unique<Connection>( auto conn = std::make_unique<Connection>(
addr, fd, addr, fd,
connectionId.fetch_add(1, std::memory_order_relaxed)); connectionId.fetch_add(1, std::memory_order_relaxed));