Search code examples
c++multithreadingqtqtcpserver

QThread and QTcpServer is that a good choice?


This is my first post here, I will try to explain my question as good as I can, don't hesitate to correct me because I'm a beginner.

I'm using Qt to design a GUI to control a 3D engine. Qt and the 3D engine talk together using a QTcpserver. I can send command to the 3D engine like "move object" or "list objects in scene" and the engine will answer.

Currently, there is 2 problems: 1) When the server respond, I cannot know if that is the response from a "move" function or for a "list" function. I parse the answer to launch event on the GUI, but that's not a proper solution. 2) Before sending a command, I call the waitForReadyRead function, which is blocking the main thread. That's why I'm posting here.

I thought about a solution: a Thread which contains a List of command and pointer on the function to call next. When I click on a UI button, it sends the command to the list whith the right function pointer and the Thread will try to empty the list sending command to the server.

But I really don't know if it's the good way to resolve my problem. I don't know much about QTcpServer and QThread, I read many articles where they are used together to handle multiple client connection but that didn't help me.

I didn't post code here because I don't think my question is "code related" but I would be happy to do so if you ask me for.

Thanks for pointing me the right direction.


Solution

  • Operations on QTcpSocket are designed to be asynchronous. Don't try to use it as synchronous objects - that's not how this class was designed. Of course, you can create a separate thread to do processing there, but simply sending commands over a socket does not warrant the overhead of threads.

    http://qt-project.org/doc/qt-5/qabstractsocket.html

    Look at the signals that are emitted, including readyRead() from QIODevice. Create a slot that will process your data and connect it to that signal. You should also handle other cases, including error handling signals and deal with connected/disconnected states.