c++ - Qt create a dialog that waits for a network event -
i writing client client/server application. clients supposed login using login window. if login successful, "waiting" window appears (this window contains label). on server side there barrier waits n clients logged in; when happens, message broadcasted, waiting window supposed close , new window appears every client.
the networking interface implemented me, using low-level functions, not functionality provided qt.
the actual waiting loop this:
char buffer[256]; while (strcmp(buffer, "proceed")) read(sockfd, buffer, 256);
the problem if start loop in main thread, application blocks, obvious reasons.
how can make loop run , not block application, , close dialog when ends?
later edit: did attempt use qthreads, but, reasons don't understand yet, application still crashes:
class waitloop : public qthread { public: waitloop(networkhandler &network) : network(network) {} private : networkhandler &network; void run() { this->network.waitforgamestart(); } };
in wait dialog constructor:
waitloop *waitloop = new waitloop(network); connect(waitloop, signal(finished()), this, slot(gamestartslot())); waitloop->start();
the application still crashes using approach.
the sanest way approach not using low-level functions, because aren't writing in c. use @ least qabstractsocket
wrap sockfd
. setsocketdescriptor
method lets it.
your code becomes non-blocking , asynchronous:
class controller : public qobject { q_object qstatemachine m_sm; qstate s_init{&m_sm}, s_proceeding{&m_sm}; qabstractsocket m_socket; q_signal void proceed(); q_slot void ondata() { auto data = m_socket.readall(); if (data.contains("proceed")) proceed(); } public: controller(qobject * parent = 0) : qobject(parent) { connect(&m_socket, &qiodevice::readyread, this, &controller::ondata); s_init.addtransition(this, &controller::proceed, &s_proceeding); m_sm.setinitialstate(&s_init); m_sm.start(); } bool setup(quintptr fd) { return m_socket.setsocketdescriptor(fd); } };
through use of state machine, it's easy add more states, react transitions (see qstate::onentry
signal, etc.), , ensure behavior correct. fleshing out uml statechart forces think handling corner cases, etc. see this answer full example.
Comments
Post a Comment