如何知道连接到QTcpServer的客户端是否已关闭连接

How to know if a client connected to a QTcpServer has closed connection?

本文关键字:连接 是否 客户端 何知道 QTcpServer      更新时间:2023-10-16

我想将数据从特定位置(共享内存)传递到客户端应用程序。线程不断地轮询SHM以获取新数据,一旦获得数据,就将其传递给客户端。

可以有这样的客户端应用程序的多个实例,这些实例将连接到我的(QTcpServer)服务器。

我计划在每次服务器接收到新连接时简单地创建一个新的QTcpSocket,并将所有这些套接字存储在一个向量中。之后,在每次成功轮询时,我将把数据写入存储在向量中的所有QTcpSocket

但是如果客户端放弃连接(关闭他的窗口),我需要知道它!否则我将继续写QTcpSocket不再存在,最终崩溃。

解决方案是什么?

QTcpServer类只有2个信号:

Signals
void    acceptError(QAbstractSocket::SocketError socketError)
void    newConnection()
2 signals inherited from QObject

您有一个包含套接字向量或列表的类。只要这个类是从QObject派生出来的,你就可以使用QTcpSocket的信号和插槽在类断开连接时通知它。

所以,我会这样做:-

class Server : public QObject
{
    Q_OBJECT
    public:
        Server();
    public slots:
        // Slot to handle disconnected client
        void ClientDisconnected(); 
    private slots:
        // New client connection
        void NewConnection();
    private:
        QTcpSocket* m_pServerSocket;
        QList<QTcpSocket*> m_pClientSocketList;
};
Server::Server()
{   // Qt 5 connect syntax
    connect(m_pServerSocket, &QTcpServer::newConnection, this, &Server::NewConnection);
}
void Server::NewConnection()
{
    QTcpSocket* pClient = nextPendingConnection();
    m_pClientSocketList.push_back(pClient);
    // Qt 5 connect syntax
    connect(pClient, &QTcpSocket::disconnected, this, &Server::ClientDisconnected);
}
void Server::ClientDisconnected()
{
    // client has disconnected, so remove from list
    QTcpSocket* pClient = static_cast<QTcpSocket*>(QObject::sender());
    m_pClientSocketList.removeOne(pClient);
}

您必须以这种方式为套接字设置TCP keepapplive选项:

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