Each week I try to complete some challenge with Qt to improve my skills. Sometimes they are easy tests to remember past knowledge that in other way I forgot, but this week what I wanted was to understand in a basic how QThread runs together with QTcpServer. To do it more difficult, I want that the QTcpServer was allowed to get connections from n clients and depending on the command sent by the client, answer to an one or answer to all the clients connected to the server. In other way a multithread would had no sense… hehehe. The classes I have done are based on the ThreadedFortuneServer example that Qt-Creator has.
... To do it more difficult,我想让QTcpServer可以允许从n个客户端获得链接,依据客户端发来的命令,向一个或所有的已链接客户端发送响应. 另一方面,多线程应该无法被感知
Constructor (without nothing to do).
Overloaded incommingConnection(int socketDescription) that creates a QTcpSocket client and stores it in a QMap<int,QTcpSocket>. The int in the map the socketDescriptor. In this method I connect the QTcpSocket::readyRead() method to my own reader method and I connect the QTcpSocket::disconnected() signal to my own method that removes the client from the map.
重载的 incommingConnection(int socketDescription)函数,创建QTcpSocket 客户端并保存在一个QMap<int,QTcpSocket>.map中的int是socketDescriptor.在这个方法中,我连接QTcpSocket::readyRead()方法到我自己的读函数,连接 QTcpSocket::disconnected() 信号到我自己的函数,用于从map中删除client.
The reader method calls a sendMulticastMessage(const QString &_msg) it was necessary.
读函数在它需要的情况下调用sendMulticastMessage(const QString &_msg) .
The overloaded QTcpServer::incomingConnection(int socketDescriptor) where I receive the connection request from the client: Here is where I create a class instance of ServerThread and connect the QThread::finished() signal to my own notification method. In addition I connect the signal that ServerThread emits when data is received to a own Server method.
The thread finished notification method that informs the application that the client is disconnected.
The slot with the message that ServerThread emites. This slot send a (simulated) multicast message to all the clients.
Overloaded QThread::run(). Here are connected the signals of the socket to read data and delete if it is disconnected. The server writes a welcom message to the client and then starts the loop waiting for readyRead socket signal while it is connected.
The readyRead method that reads the information from client and acts depending of the message type.
Create a Protocol class for the messages sent by clients in order to be more efficient.
Add a logger that creates a .log file and truncates it in 1 MB files. Must be thread-safe!