Search code examples
multithreadingqtsocketsqtcpsocketqtcpserver

When creating a QTcpServer that allows for multiple connections, why do I need to make a socket in a new thread?


I'm using Qt 5.6. I'm working on a simple chat application and came across several places online all saying you have to create a new thread to contain QTcpSocket to handle all the new connections in a new thread.

I'm trying to figure out why you can't just use a QList of QTcpSockets to handle all the connections. Can someone please explain to me why?

If I'm mistaken, and that is a perfectly fine thing to do, please tell me that as well.

Thanks in advance.


Solution

  • Using of multithreading tcp server or using one thread tcp server depends on your task. In some tasks enough one thread and you can "just use a QList of QTcpSockets". Main characteristics of such tasks are:

    1. Small number of simultaneous incoming connections. (Critical number of simultaneous incoming connections when you must use multithreading also depends of your task. But I am convinced, that when you have more than 10 simultaneous incoming connections, you should take thought about multithreading.)
    2. Low network load / low network interactions.

    In other case it's better to do your tcp server with opportunity of making some jobs in parallel. How many connections you will be have in one thread depends of your task, but make very high number of threads is also bad idea, because then you get problems with performance. Many time will be spend to context switching.

    I think, in your case you can use the simplest variant and "just use a QList of QTcpSockets"