c++ - Qt: Is waitForReadyRead/waitForBytesWritten necessary in a synchronous UDP socket? -
the qudpsocket can used without event loop in sync mode. , found example below:
#include <qudpsocket> #include <qtextstream> int main() { qtextstream qout(stdout); qudpsocket *udpsocket = new qudpsocket(0); udpsocket->bind(3838, qudpsocket::shareaddress); while (udpsocket->waitforreadyread(-1)) { while(udpsocket->haspendingdatagrams()) { qbytearray datagram; datagram.resize(udpsocket->pendingdatagramsize()); qhostaddress sender; quint16 senderport; udpsocket->readdatagram(datagram.data(), datagram.size(), &sender, &senderport); qout << "datagram received " << sender.tostring() << endl; } } }
my question is: waitforreadyread necessary here? can use while(1) instead if not worrying cpu consumption? if need write, necessary add waitforbyteswritten?
i used work tcp sockets in sync mode under qt, not work @ without waitforreadyread call.
yes. sockets internally use non-interrupting platform notfications, , these fire when event loop has control of thread. choices are:
write asynchronous code using c++11 lambdas/closures keep code concise without need explicit helper objects. or write qt 4-style async code explicit
qobject
s provide handler slots.write pseudosynchronous code using
waitforxxxx
methods, caveat methods ofqobject
s running on same thread may need reentrant.use native networking apis.
Comments
Post a Comment