我对QT5.7.1上的Lambda和timer有一种奇怪的行为。可能是我搞错了。
我用一个套接字启动一个连接,并设置一个计时器来检查它在一定时间之后是否连接。
插座连接的信号将使时间停止。
但是,通过下面的实现,即使调用了连接的信号,定时器也不会停止。
constructor:
m_connectTimeout.setInterval(5000);
connect(&m_socket, &QLocalSocket::connected, [&]()
{
// this is called first and should stop the timer.
m_connectTimeout.stop();
});
connect(&m_connectTimeout, &QTimer::timeout, [&](){
// this is still called
});下面是一个问题可在Qt5.7.1和Windows 10上重现的最小示例。
#include <QtCore>
#include <QtNetwork>
#define PIPENAME "testbug"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QTimer timer;
QLocalSocket socketClient, *socketServer;
QLocalServer server;
timer.setInterval(2000);
QObject::connect(&timer, &QTimer::timeout, [&]
{
qDebug() << "client connection timed out";
timer.stop();
});
QObject::connect(&socketClient, &QLocalSocket::connected, [&]
{
qDebug() << "client connected";
timer.stop();
});
QObject::connect(&server, &QLocalServer::newConnection, [&]
{
qDebug() << "server got connection";
socketServer = server.nextPendingConnection();
});
server.setSocketOptions(QLocalServer::WorldAccessOption);
server.listen(PIPENAME);
qDebug() << "client connecting. . .";
socketClient.connectToServer(PIPENAME, QLocalSocket::ReadWrite);
timer.start();
return a.exec();
}程序的输出:
client connecting. . .
client connected
server got connection
client connection timed out我还注意到,它并不总是可以复制的,而且似乎是随机的。
发布于 2017-01-18 02:22:33
实际上,代码似乎工作正常,只是连接太快了,所以timer.stop在timer.start之前被调用。
在调用连接到服务器之前启动计时器似乎解决了这个问题。
m_timer.start();
m_socketClient.connectToServer(PIPENAME, QLocalSocket::ReadWrite);这意味着connectToServer在后台对事件循环执行一些调用,允许调用时隙,甚至在执行下一行之前。
https://stackoverflow.com/questions/41695554
复制相似问题