TCP Keep-alive未检测到死客户端

时间:2012-11-15 09:31:45

标签: c networking tcp keep-alive

我在服务器中添加了Keep-alive消息以了解客户端。在我的程序服务器中继续运行并向客户端发送数据。我的问题是,如果客户端断开连接服务器永远不会知道客户端断开连接。

下面是我添加了keepalive的代码片段

if ((newConnSD = ::accept(sockDesc, NULL, 0)) < 0) {
        throw SocketException("Accept failed (accept())", true);

 //TIMEOUT SETTING
 int buffersize = 4096;  

  setsockopt(sockDesc, SOL_SOCKET, SO_SNDBUF, (char *)&buffersize, 4);


 // KEEP ALIVE IMPLEMENTATION
  struct tcp_keepalive alive;
  DWORD dwBytesRet = 0;

    alive.onoff = TRUE;
    alive.keepaliveinterval = 1000;

    alive.keepalivetime = 60000;

    if (WSAIoctl(sockDesc, SIO_KEEPALIVE_VALS, &alive, sizeof(alive), NULL, 0,
    &dwBytesRet, NULL, NULL) == SOCKET_ERROR)
    {
        printf("WSAIotcl(SIO_KEEPALIVE_VALS) failed; ");
        LOG4CXX_INFO(loggerToFile,"WSAIotcl(SIO_KEEPALIVE_VALS) failed ");
        cout<<WSAGetLastError()<<endl;

    }
    else
    {
        LOG4CXX_INFO(loggerToFile,"WSAIotcl(SIO_KEEPALIVE_VALS) Success ");
        cout<<"WSAIotcl(SIO_KEEPALIVE_VALS) Success " <<endl;
    }

  int optval;
   socklen_t optlen = sizeof(optval);
  /* Set the option active */
   optval = 1;
   optlen = sizeof(optval);
   if(setsockopt(sockDesc, SOL_SOCKET, SO_KEEPALIVE,(char*)&optval, optlen) < 0) {

       cout<<"Error while setting KEEP_ALIVE Message"<<endl;
       LOG4CXX_INFO(loggerToFile,"Error while setting KEEP_ALIVE Message");

   }
   else
   {
       LOG4CXX_INFO(loggerToFile,"SO_KEEPALIVE set on socket");
        cout<<"SO_KEEPALIVE set on socket"<<endl;
   }


 printf("SIO_KEEPALIVE_VALS set:\n");  

0 个答案:

没有答案