【问题标题】:How to know if a client connected to a QTcpServer has closed connection?如何知道连接到 QTcpServer 的客户端是否已关闭连接?
【发布时间】:2014-08-16 12:01:31
【问题描述】:

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

可能有多个此类客户端应用程序实例将连接到我的 (QTcpServer) 服务器。

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

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

这里的解决方案是什么?

QTcpServer 类中只有 2 个信号:

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

【问题讨论】:

  • 您的套接字上需要某种形式的TCP keep alive
  • 是的,知道在 Qt 中怎么可能没有吗?

标签: c++ qt networking tcp network-programming


【解决方案1】:

您有一个包含套接字的向量或列表的类。只要这个类是从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);
}

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 您可能想评论一下它的作用以及您认为它可能有助于解决这种情况的原因,以使您的答案更可行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-04
    • 2023-04-11
    • 1970-01-01
    • 2017-05-09
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多