Important: Please read the Qt Code of Conduct -

QTcpServer that responds to multiple QTcpSockets at the same time.

  • I am developing a QTcpServer which will forward TCP data to another server which takes -/+ 1min to respond. The problem is when the data comes back, I have to send it to the correct socket which requested the data.

    What my server does is strip the authentication data or login details every time a request or data is sent from the client. after validating the data on the MYSQL database i have to forward it to another server as an HTTP request. When the response arrives 1 - 2 mins later, i have to write it back on the correct server.

    Is there any kind of approach i can take for my QTcpServer to be able to know which Socket requested what data and be able to respond to the correct one when the data return from another server.

    Please advise.

  • Lifetime Qt Champion


    What are you using to send the request to that other server ?

  • @SGaist , It's running AJAX so am using QNetworkRequest to make a XmlHttpRequest.

  • you can use QAbstractSocket::socketDescriptor() as ID of the destination but you will need a way to link a request to a response i.e. when an answer comes back to you you have to find a way to identify what the question was


    • establish connection between server and HTTP server


    • started when connection is enstablished between Server and Client
    • receives the requests, passes it to thread 1 together with its socketDescriptor


    • receives the request, stores the socketDescriptor to remember who asked the question
    • receives the answer, it finds out what the question was and who asked it
    • sends the response to the socket with the asker socketDescriptor


    • receives the replay and forwards it to the client

  • Lifetime Qt Champion

    Wouldn't a QMap<QNetworkReply *, QTcpSocket *> be enough ? That way it would be possible to associate the reply of the secondary request to the socket where the original stuff is coming from.

  • @SGaist said in QTcpServer that responds to multiple QTcpSockets at the same time.:

    Wouldn't a QMap<QNetworkReply *, QTcpSocket *> be enough ?

    Depends if the bottleneck is waiting for the response or "validating the data on the MYSQL database"

  • @VRonin using the Threading technique, how do i make sure that Thread 2 doesn't respond to two requests at the same time, which i think will crash the application. using QMutex ?

  • You could build a queue. requests come in, they get queued together with who asked it and thread 2 will process the queue

  • Moderators

    Use a session object. Look here for a full example of a threaded TCP server.

Log in to reply