Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Writing a Chat Application in C++



  • Hello,
    I am trying to make a chat application. I use Qt (for the GUI) and Boost.Asio (for socket programming function calls).
    I want to establish a connection between the client and server before I show the client's GUI. However, when I set up the connection, I use a function called io_service.run() which is a blocking call. Basically, it is an event loop queueing and executing read and write messages. Since this is a blocking call, it will not reach a.exec() which shows the GUI. So I end up with a black window, instead of the GUI.

    How do I fix this?
    Thank you. :)



  • @pokemon123

    Why you want to use Asio? You can do the whole Chat App (GUI + network connection) with Qt only.
    https://doc.qt.io/qt-5/qtnetwork-network-chat-example.html

    a.exec() will start its own event loop for GUI, so it's not that easy to make io_service.run() work with Qt.

    You could try to run your io_service in a different boost::thread, but I don't know, if everything will work as expected



  • Another option (if you are bound and determined to use as few threads as humanly possible, for whatever reason you may have):

    You can use a QTimer that "ticks" every N milliseconds (you choose N), and you can invoke other methods on your io_service instance instead of invoking run(). For example you could use io_service::run_for to constrain the length of "timeslice" you yield to the io_service.

    There are a number of similar methods, such as run_one, poll, and poll_one.

    In this way, you can achieve a sort of cooperative, voluntary yielding, time-slicing where the io_service uses the main/GUI thread, but it never blocks it for very long.


Log in to reply