TCP,尽管有KEEPALIVE,recv功能仍挂起 [英] TCP, recv function hanging despite KEEPALIVE

查看:212
本文介绍了TCP,尽管有KEEPALIVE,recv功能仍挂起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在服务器死机之后,TCP keepalive(具有较小的超时)是否可以防止客户端挂在recv上?

Is TCP keepalive (with small timeouts) preventing client from hanging on recv, after the server is dead?

场景:

在单独的计算机上运行的服务器和客户端:

Server and client running on separate machines:

  1. 客户端通过带有KEEPALIVE选项的TCP通过服务器连接到服务器
  2. 客户端发送"Hello服务器"并等待响应
  3. 服务器收到"Hello服务器"并响应"Hello客户端"
  4. 客户端收到响应,睡眠10秒钟,然后重复执行步骤2-4(现在跳过了步骤1-已保留连接)

现在,在客户端睡眠期间,服务器已关闭:

During the client sleep, the server is plugged off, now:

  1. 客户端唤醒
  2. 发送"Hello服务器"并等待响应
  3. 20分钟后recv放弃-我期望KEEPALIVE在 45秒后 会中断recv功能:

设置KEEPALIVE选项:

Setting KEEPALIVE options:

void TCPclient::setkeepalive()
{
   int optval;
   socklen_t optlen = sizeof(optval);

   /* Check the status for the keepalive option */
   if(getsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &optval, &optlen) < 0) {
        throw std::string("getsockopt");
   }

   optval = 1;
   optlen = sizeof(optval);
   if(setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &optval, optlen) < 0) {
      close(s);
      exit(EXIT_FAILURE);
   }

    optval = 2;
    if (setsockopt(sock, SOL_TCP, TCP_KEEPCNT, &optval, optlen) < 0) {
        throw std::string("setsockopt");
    }

    optval = 15;
    if (setsockopt(sock, SOL_TCP, TCP_KEEPIDLE, &optval, optlen) < 0) {
        throw std::string("setsockopt");
    }

    optval = 15;
    if (setsockopt(sock, SOL_TCP, TCP_KEEPINTVL, &optval, optlen) < 0) {
        throw std::string("setsockopt");
    }   
}

linux 3.2.0-84-generic

推荐答案

当线路空闲15秒钟时,Keepalive处于活动状态.在您的情况下,Keepalive启动超时为15秒,睡眠为10秒,这意味着"Hello服务器"将是服务器被杀死后要发送的下一个命令.

Keepalive becomes active when the line has been idle for 15 secs. In your case Keepalive kick off timeout is 15 secs, the sleep is 10 secs, which means "Hello server" will be the next command to be sent after the server is killed.

您的Linux将尝试多次重传该消息. Keepalive仍然不会被触发.达到重试次数限制后,连接将中断-这将需要10到30分钟.

Your Linux will try to retransmit the message several times. Keepalive still won't be triggered. The connection will break after the limit of retries is reached - that will take 10-30 minutes.

这篇关于TCP,尽管有KEEPALIVE,recv功能仍挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆