问题描述
如何在没有 UI 挂起的情况下将 Qtcpsockets 连接到大约 100 个服务器?
当我创建 100 个 QTcpsockets 以连接到每个服务器并调用 connectToHost() 函数时,QDialog 卡住了。有没有办法将 connectToHost() 部分作为后台作业运行?
因此,所有连接都已建立,但在尝试连接时(调用 connectToHost(),UI 处于“无响应”状态。
// onConnectToICPMC is the slot function connected to the dialog button pressed signal
void WidgetUploadFile::onConnectToICPMC()
{
// m_tcpClients is a QVector containing a custm QObject Class that manages QTcpsocket
for(int i = 0; i < m_tcpClients.size(); ++i)
{
if(m_tcpClients.at(i)->state() != QAbstractSocket::ConnectedState)
{
m_tcpClients.at(i)->connectToServer(); // Call the connectToHost() function of QTcpsocket.
}
emit sendConnProgBarUpdate(i+1);
emit sendCurrentSockLog(m_tcpClients.at(i)->ipAddress(),m_tcpClients.at(i)->state());
}
}
在每个 QTcpsocket 连接到服务器时挂起的对话框。:
毕竟QTcpsockets尝试连接到服务器:
解决方法
不应该在主线程上运行耗时的任务。在这种情况下,有两种策略:
- 线程的使用。
- 分成子任务,每 T 秒分部分执行。
在这种情况下,我认为使用 QTimeLine
的第二个选项是最好的。
*.h
private:
void handleFrameChanged(int i);
QTimeLine timeLine;
*.cpp
{
// constructor
timeLine.setRange(0,m_tcpClients.size()-1);
connect(&timeLine,&QTimeLine::frameChanged,this,&WidgetUploadFile::handleFrameChanged);
}
void WidgetUploadFile::onConnectToICPMC()
{
timeLine.start();
}
void WidgetUploadFile::handleFrameChanged(int i){
auto client = m_tcpClients.at(i);
if(client->state() != QAbstractSocket::ConnectedState){
client->connectToServer();
}
emit sendConnProgBarUpdate(i + 1);
emit sendConnProgBarUpdate(client->ipAddress(),client->state());
}