这个问题是一个非常古老的问题,但也许它仍然有帮助。
关于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创建一个新线程。服务器和套接字通过信号和插槽连接。 –