如何知道连接到QTcpServer的客户端是否已关闭连接
How to know if a client connected to a QTcpServer has closed connection?
我想将数据从特定位置(共享内存)传递到客户端应用程序。线程不断地轮询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);
相关文章:
- 是否有 Windows 用户空间函数来枚举连接的网络共享?
- 某些 boost::asio 异步函数是否将处理程序连接到操作,以便处理程序被触发一次?
- 如何在 c++ 中确定 tcp 客户端是否连接
- SDLnet检查TCPsocket是否已关闭连接
- 如果代码中没有连接任何插槽,是否有理由发出Qt信号?
- TCP/IP 客户端是否可以连接到无法访问的 IP
- 将 QObject 用作类成员并将该成员用作连接的上下文是否安全?
- 如何检查LLDB是否可以连接到二进制
- 如何在C API中检查MySql连接是否处于活动状态
- C++ODBC检查连接是否成功
- 在读取期间,非重叠串行端口连接是否会阻止写入(反之亦然)
- 如何在C++中检测我的局域网连接是否断开
- 检查连接是否在libpqxx(postgres)中处于活动状态
- 如何确定阻塞的 SSL BIO 连接是否已关闭
- 在哪里建立连接是否重要
- 如何知道TCP连接是否存在于同一机器上的两个进程之间
- 如何检查连接是否丢失
- 如何确定与套接字的连接是否已关闭
- 头可连接连接是否可以具有争用条件?你如何绕过它
- 数据库连接是否可以重用