這個問題是一個非常古老的問題,但也許它仍然有幫助。
關於Qt中的線程:
很多人認爲關於Qt的並行處理像在.NET中,你需要爲每個操作另一個線程,在QT這是沒有必要的!
Qt中你只需要一個線程,如果你有這樣計算的大事情或者從一個SQLServer
等待爲SYNCRON一個答案,如果我有正確理解你,你沒有這樣的阻塞操作阻塞代碼。
所以我有編程的一個非常小的TCPSERVER沒有繼承,沒有一個單獨的線程(當然,除了主事件循環線程),它有望解決您的問題,並幫助他人:
#include <QObject>
#include <QSet>
#include <QTcpServer>
#include <QTcpSocket>
#include <QTimer>
class TcpServer : public QObject
{
Q_OBJECT
public:
TcpServer()
{
// handle new connections
this->connect(&this->serverTcp, &QTcpServer::newConnection, this, &TcpServer::handleClientConnect);
// init client refresh timer
this->timer.setInterval(1000);
this->connect(&this->timer, &QTimer::timeout, this, &TcpServer::handleClientUpdates);
this->timer.start();
}
bool startListen(qint16 port)
{
return this->serverTcp.listen(QHostAddress::Any, port);
}
private slots:
void handleClientConnect()
{
QTcpSocket* socketClient = *this->setConnectedClients.insert(this->serverTcp.nextPendingConnection());
this->connect(socketClient, &QTcpSocket::disconnected, this, &TcpServer::handleClientDisconnect);
this->connect(socketClient, &QTcpSocket::readyRead, this, &TcpServer::handleClientData);
}
void handleClientDisconnect()
{
this->setConnectedClients.remove((QTcpSocket*)this->sender());
}
void handleClientData()
{
QTcpSocket* socketSender = (QTcpSocket*)this->sender();
// handle here the data sent by the client
}
void handleClientUpdates()
{
// construct here your update data
QByteArray baUpdateResponse = "test";
// send update data to all connected clients
foreach(QTcpSocket* socketClient, this->setConnectedClients) {
socketClient->write(baUpdateResponse);
}
}
private:
QTcpServer serverTcp;
QTimer timer;
QSet<QTcpSocket*> setConnectedClients;
};
有一次,我做了TCP上傳服務器哪些客戶端可以上傳文件。我有一個QTcpServer和許多QTCPSockets。我創建了一個派生自QTCPSocket的類,並具有一些數據接收功能。和你一樣,當服務器接收到一個傳入連接時,它爲具有線程ID或套接字ID的QTCPSocket創建一個新線程。服務器和套接字通過信號和插槽連接。 –