[英]May a single-threaded application time out trying to connect a QTcpSocket to its own QTcpServer in blocking mode?
I need to test a feature in my library that requires usage of sequential QIODevices. 我需要在我的库中测试需要使用顺序QIODevices的功能。 I have written code like this: 我写了这样的代码:
QTcpServer server;
QVERIFY(server.listen());
quint16 port = server.serverPort();
QTcpSocket socket;
socket.connectToHost(QHostAddress(QHostAddress::LocalHost), port);
QVERIFY(socket.waitForConnected());
QVERIFY(server.waitForNewConnection(30000));
QTcpSocket *client = server.nextPendingConnection();
// send some data to socket
socket.disconnectFromHost();
QVERIFY(socket.waitForDisconnected());
QVERIFY(client->waitForReadyRead());
QByteArray received = client->readAll();
client->close();
// check the data received
So far it seems to work (tested in Win7x64/MSVS2012 and Ubuntu/GCC). 到目前为止,它似乎仍然有效(在Win7x64 / MSVS2012和Ubuntu / GCC中进行了测试)。 However, I am worried about this particular part: 但是,我担心这部分内容:
QVERIFY(socket.waitForConnected());
QVERIFY(server.waitForNewConnection(30000));
Can't this thing sort of dead-lock (well, actually, time-out)? 这东西不能陷入僵局(实际上,是超时)吗? As far as I know, waitForConnected()
tries to perform a connection in non-blocking mode and then call select() or poll() or whatever to actually get the job done. 据我所知, waitForConnected()
尝试在非阻塞模式下执行连接,然后调用select()或poll()或任何其他方法来实际完成工作。 Meanwhile, on the other side someone has to call accept()
for the waitForConnected()
call to succeed, right? 同时,另一方面,有人必须调用accept()
才能使waitForConnected()
调用成功,对吗? In this case, this someone is the next line calling waitForNewConnection()
. 在这种情况下,此人是下一行调用waitForNewConnection()
。 But this line is only executed after the connection is successfully established. 但是仅在成功建立连接后才执行此行。 As far as I understand it, it works because the OS accepts my connection on the TCP level nevertheless without actually waiting for the accept()
call. 据我了解,它之所以有效,是因为OS仍然在TCP级别上接受我的连接,而无需实际等待accept()
调用。
Can this behavior be relied upon or it may suddenly time out on some systems? 是否可以依靠这种行为,或者在某些系统上可能突然超时? I really don't want to go into the world of slots and signals just for this one test, as it will make it much more complicated. 我真的不想仅仅为了这项测试而进入插槽和信号的世界,因为这会使它变得更加复杂。
If you in fact want non-sequential devices, then sockets are entirely the wrong thing to use. 如果实际上您需要非顺序设备,那么使用套接字完全是错误的选择。 You want a QBuffer
. 您需要一个QBuffer
。 Sockets are sequential, not random-access. 套接字是顺序的,不是随机访问的。
If you made a typo and do want a sequential device, then simply subclass QBuffer
and override its isSequential
method to return true. 如果您QBuffer
了isSequential
并确实要使用顺序设备,则只需将QBuffer
子类QBuffer
并重写其isSequential
方法即可返回true。
Your code as written is correct. 您编写的代码是正确的。 You could use QLocalServer
and QLocalSocket
instead, or even write a simple QIODevice
pair yourself. 您可以改用QLocalServer
和QLocalSocket
,甚至自己编写一个简单的QIODevice
对。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.