QTcpSocket保持活动选项不起作用

时间:2016-12-20 08:50:13

标签: sockets keep-alive linuxmint qtcpsocket

我有一个简单的程序,因为我的客户端包含一个tcp套接字(QTcpSocket)。我的客户代码如下:

/// Set keepAlive
int enableKeepAlive = 1;
/* Set socket FD's option OPTNAME at protocol level LEVEL
   to *OPTVAL (which is OPTLEN bytes long).
   Returns 0 on success, -1 for errors.  */
qDebug() << setsockopt(*socketDescriptor, SOL_SOCKET, SO_KEEPALIVE, &enableKeepAlive, sizeof(enableKeepAlive));

int maxIdle = 1; /// Seconds
qDebug() << setsockopt(*socketDescriptor, SOL_TCP, TCP_KEEPIDLE, &maxIdle, sizeof(maxIdle));

int count = 1;  /// Send up to 1 keepalive packets out, then disconnect if no response
qDebug() << setsockopt(*socketDescriptor, SOL_TCP, TCP_KEEPCNT, &count, sizeof(count));

int interval = 1;  /// Send a keepalive packet out every 1 seconds (after the 1 second idle period)
qDebug() << setsockopt(*socketDescriptor, SOL_TCP, TCP_KEEPINTVL, &interval, sizeof(interval));

下面给出了setSocketOption:

tcp        0      0 192.168.2.157:37281     192.168.2.163:4444      ESTABLISHED keepalive (0.16/0/0)

当我运行程序时,一切看起来都很好,并且我的套接字将启用keepalive选项。但是当我在客户端拔掉电缆时,它不起作用。我已经将我的netstat输出带到了下面,这表明我的套接字启用了keepalive定时器。

Caused by: java.io.IOException: Failed to create local dir in /tmp/blockmgr-bb765fd4-361f-4ee4-a6ef-adc547d8d838/28 

我还在服务器端启用了keepalive选项,就像客户端一样。现在我有一些问题; 1-当我应该启用keepalive选项?连接到服务器后或连接之前? 2-我应该在程序中编写一些用于捕获keepalive错误的代码吗?

顺便说一句,我的程序在linux mint 17.1中运行,我还将sysctl.conf和proc / sys中的keeplalive选项更改为no vail。

提前感谢您的帮助。 礼

1 个答案:

答案 0 :(得分:0)

最好使用Qt的功能setSocketOption

your_socket->setSocketOption(QAbstractSocket::KeepAliveOption, 1);
  

枚举QAbstractSocket :: SocketOption

     

此枚举表示可以在套接字上设置的选项。如果   在接收到connected()信号后,可以设置它们   从套接字或从a接收到新套接字后   QTcpServer既可。

     

注意:在Windows运行时,必须在连接套接字之前设置QAbstractSocket :: KeepAliveOption。

并且用于捕获任何连接错误:

connect (your_socket, static_cast<void (QTcpSocket::*)(QAbstractSocket::SocketError)>(&QAbstractSocket::error), this, &YourClass::onError);
// ...

void YourClass::onError(QAbstractSocket::SocketError socketError)
{
    switch(socketError)
    {
        case QAbstractSocket::ConnectionRefusedError:
        // ...
        // ...
    }
}