我有一个QTcpSocket,我正在读一个循环.每次读取完整数据包或出现错误时,我都会手动检查循环内套接字的状态:
while(true){
if(socket->state()==QAbstractSocket::ConnectedState){
qDebug()<<"Socket status: connected. Looking for packets...";
if(socket->waitForReadyRead(2000)){
//...
}
Run Code Online (Sandbox Code Playgroud)
当我执行de program时,一旦连接并且循环开始,它总是打印qDebug()<<"Socket status: connected. Looking for packets..."; 然后停留,waitForReadyRead直到一些数据准备好被读取.
问题是没有检测到断开连接.如果我断开网络与操作系统选项的连接,或者即使我拔掉以太网线,它的行为也是一样的:套接字状态等于QAbstractSocket::ConnectedState,所以它会继续,但当然没有收到任何东西.
我还试图检测连接disconnected()信号(在第一次连接后)到重新连接功能的断开连接:
// Detect disconnection in order to reconnect
connect(socket, SIGNAL(disconnected()), this, SLOT(reconnect()));
void MyClass::reconnect(){
qDebug()<<"Signal DISCONNECTED emitted. Now trying to reconnect";
panelGUI->mostrarValueOffline();
socket->close();
prepareSocket((Global::directionIPSerialServer).toLocal8Bit().data(), 8008, socket);
qDebug()<<"Reconnected? Status: "<<socket->state();
}
Run Code Online (Sandbox Code Playgroud)
但是信号永远不会被发出,因为这段代码永远不会被执行.这是合乎逻辑的,因为看起来套接字状态总是如此ConnectedState.
如果我再次插入,连接将恢复并再次开始接收数据,但我确实想检测断开连接以在GUI上显示"已断开连接".
为什么QTcpSocket会以这种方式运行,我该如何解决这个问题呢?
编辑:我在类构造函数中创建套接字,然后初始化调用prepareSocket函数:
socket = new QTcpSocket();
socket->moveToThread(this);
bool prepareSocket(QString address, int port, QTcpSocket *socket) {
socket->connectToHost(address, port); …Run Code Online (Sandbox Code Playgroud)