Multi-client / server tcp application using qt

偶尔善良 提交于 2019-12-19 11:02:43

问题


i am working on a project that requires tcp communication between a "master" application and a number of "servants". (the project is in c++ and i am also using qt)

The "servants" will do some processing and send their results to the "master". So far it's a straightforward multi client-server app.

The thing is that at random times, the master will request some extra info from the servants, and even send them info to change the way they process.

if i base my project on the fortune client/server examples, will i be able to send messages to the servants from the master? (any ideas on how?)

or do i need to base my work on something else (like the chat client maybe?)?

any other suggestions on tcp client/server communication are welcome, but since i already use qt, i would prefer not to add other libs....

thank you in advance!


回答1:


to build a server in Qt is very simple. you have to derive QTcpServer and implement some methods or slot. This is valid for the clients too. Derive QTcpSocket and you will have your client.

in example, to detect a client incoming you implement virtual void incomingConnection ( int socketDescriptor ) .so in your case you can save clients incoming in a map(a map because every client will have his own id).

in both server and client you will probably want to implement readyRead() slot. this slot do the communication thing that you want. in fact inside this slot the server can receive and send to client messages and vice-versa.

this is a tipical readyread :

  void Client::readyRead() {
     while (this->canReadLine()) {
            // here you get the message from the server
        const QString& line = QString::fromUtf8(this->readLine()).trimmed();
     }
 }

this is how to send messages:

void Client::sendMessage(const QString& message) {
    this->write(message.toUtf8());
    this->write("\n");
}

That s all!



来源:https://stackoverflow.com/questions/13762222/multi-client-server-tcp-application-using-qt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!