Search code examples
c++qttcpclient-server

Multi-client / server tcp application using qt


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!


Solution

  • 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 its 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 typical 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!