前言
QTcpSocket在windows下waitForConnected、 waitForDisconnected、waitForBytesWritten、waitForReadyRead这四个函数在windows下可能失效。如waitForReadyRead函数,文档中提到:
Note: This function may fail randomly on Windows. Consider using the event loop and the readyRead() signal if your software will run on Windows.
这里需要自己使用eventLoop重新实现一下这四个函数。以waitForReadyRead函数为例:
关键代码
这里直接重写waitForReadyRead()这个虚函数。
bool WinTcpSocket::waitForReadyRead(int msecs)
{
QEventLoop loop;
QTimer timer;
connect(this, &WinTcpSocket::readyRead,&loop,&QEventLoop::quit);
connect(&timer,&QTimer::timeout,[&loop]{loop.exit(1);});
timer.start(msecs);
return !loop.exec();
}
注意事项
注意这里不要使用QTimer::singleShot()这种静态函数的方式,否则获取到readyRead信号后loop的exec函数已经退出,定时器又没有停止,定时器超时后还会去获取已经释放掉的内存,造成程序崩溃。
bool WinTcpSocket::waitForReadyRead(int msecs)
{
QEventLoop loop;
connect(this, &WinTcpSocket::readyRead,&loop,&QEventLoop::quit);
QTimer::singleShot(msecs,[&loop]{loop.exit(1);});
return !loop.exec();
}
完整代码
头文件:
#ifndef WINTCPSOCKET_H
#define WINTCPSOCKET_H
#include <QTcpSocket>
//主要解决QTcpsocket在windows下几个同步函数失效的问题
class WinTcpSocket:public QTcpSocket
{
public:
WinTcpSocket(QObject *parent = nullptr);
virtual bool waitForReadyRead(int msecs = 30000);
virtual bool waitForBytesWritten(int msecs = 30000);
virtual bool waitForDisconnected(int msecs = 30000);
virtual bool waitForConnected(int msecs = 30000);
};
#endif // WINTCPSOCKET_H
#include "wintcpsocket.h"
#include <QEventLoop>
#include <QTimer>
#include <QMetaMethod>
WinTcpSocket::WinTcpSocket(QObject *parent):QTcpSocket (parent)
{
}
bool WinTcpSocket::waitForReadyRead(int msecs)
{
#ifdef Q_OS_WIN32
QEventLoop loop;
QTimer timer;
connect(this, &WinTcpSocket::readyRead,&loop,&QEventLoop::quit);
connect(&timer,&QTimer::timeout,[&loop]{loop.exit(1);});
timer.start(msecs);
return !loop.exec();
#else
return QTcpSocket::waitForReadyRead(msecs);
#endif
}
bool WinTcpSocket::waitForBytesWritten(int msecs)
{
#ifdef Q_OS_WIN32
QEventLoop loop;
QTimer timer;
connect(this, &WinTcpSocket::bytesWritten,&loop,&QEventLoop::quit);
connect(&timer,&QTimer::timeout,[&loop]{loop.exit(0);});
timer.start(msecs);
return !loop.exec();
#else
return QTcpSocket::waitForReadyRead(msecs);
#endif
}
bool WinTcpSocket::waitForDisconnected(int msecs)
{
#ifdef Q_OS_WIN32
QEventLoop loop;
QTimer timer;
connect(this, &WinTcpSocket::disconnected,&loop,&QEventLoop::quit);
connect(&timer,&QTimer::timeout,[&loop]{loop.exit(0);});
timer.start(msecs);
return !loop.exec();
#else
return QTcpSocket::waitForReadyRead(msecs);
#endif
}
bool WinTcpSocket::waitForConnected(int msecs)
{
#ifdef Q_OS_WIN32
QEventLoop loop;
QTimer timer;
connect(this, &WinTcpSocket::connected,&loop,&QEventLoop::quit);
connect(&timer,&QTimer::timeout,[&loop]{loop.exit(0);});
timer.start(msecs);
return !loop.exec();
#else
return QTcpSocket::waitForReadyRead(msecs);
#endif
}