套接字keepalive不工作

我有一个客户端连接()到服务器,并在空闲时,超过几个小时后。 我用1秒加了setsockopt(socket,SOL_SOCKET,SO_KEEPALIVE …),但是没有什么区别。 任何线索为什么Keepalive不会工作? 如果我使用SOL_TCP而不是SOL_SOCKET,它会有所作为吗? 这是在Linux上。

Solutions Collecting From Web of "套接字keepalive不工作"

int val = 1; setsockopt(socket, SOL_SOCKET, SO_KEEPALIVE, &val, sizeof val) 

只是启用Keepalive。 您将获得keepalive探针的默认计时器,您可以使用以下命令查看它们:

 sysctl net.ipv4.tcp_keepalive_time 

通常默认是几个小时。

如果你想改变默认的定时器,你可以使用这个:

 struct KeepConfig cfg = { 60, 5, 5}; set_tcp_keepalive_cfg(fd, &cfg); 

辅助函数在这里:

 struct KeepConfig { /** The time (in seconds) the connection needs to remain * idle before TCP starts sending keepalive probes (TCP_KEEPIDLE socket option) */ int keepidle; /** The maximum number of keepalive probes TCP should * send before dropping the connection. (TCP_KEEPCNT socket option) */ int keepcnt; /** The time (in seconds) between individual keepalive probes. * (TCP_KEEPINTVL socket option) */ int keepintvl; }; /** * enable TCP keepalive on the socket * @param fd file descriptor * @return 0 on success -1 on failure */ int set_tcp_keepalive(int sockfd) { int optval = 1; return setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &optval, sizeof(optval)); } /** Set the keepalive options on the socket * This also enables TCP keepalive on the socket * * @param fd file descriptor * @param fd file descriptor * @return 0 on success -1 on failure */ int set_tcp_keepalive_cfg(int sockfd, const struct KeepConfig *cfg) { int rc; //first turn on keepalive rc = set_tcp_keepalive(sockfd); if (rc != 0) { return rc; } //set the keepalive options rc = setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPCNT, &cfg->keepcnt, sizeof cfg->keepcnt); if (rc != 0) { return rc; } rc = setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE, &cfg->keepidle, sizeof cfg->keepidle); if (rc != 0) { return rc; } rc = setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPINTVL, &cfg->keepintvl, sizeof cfg->keepintvl); if (rc != 0) { return rc; } return 0; } 

尽管名字叫做keep-alive,但并不是保持连接的活跃,而是定期交换数据包,以确保对等体之间存在网络路径。 它杀死了连接,可以在空闲时延长网络中断。

由于这种行为,除非有充分的理由,如telnet或SSH连接,当客户端失去联系时合理地终止会话,否则不应该使用keep-alive。

大多数情况下,由于某些连接处理策略,服务器会在n小时后关闭连接,而不管存活使用情况如何。