QTcpSocket在不阻塞GUI的情况下重新连接到服务器
QTcpSocket reconnect to server without blocking GUI
我有一个客户端-服务器应用程序,当服务器先于客户端启动时,它就像一个魅力,但由于我不知道服务器是否首先启动,我需要客户端继续尝试连接到服务器,而不阻塞接口。到目前为止,我想到的最好的事情是做一个像这样的循环
void client::initConnection(){
connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readMessage()));
connect(tcpSocket, SIGNAL(connected()), this, SLOT(clientConnected()));
connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(disconnectedFromHost()));
while (tcpSocket->state() != QAbstractSocket::ConnectedState) {
tcpSocket->abort();
tcpSocket->connectToHost(address, port, QIODevice::ReadWrite);
tcpSocket->waitForConnected(1000);
}
}
但是,如果我在主线程中调用这段代码,它会阻塞gui(原因很明显(,我想我可能必须使用线程,但似乎真的不可能从不同于创建套接字的线程中使用套接字。所以,也许有一种方法可以在不阻塞gui和更改应用程序架构的情况下运行这种方法?
您可以使用client
类(看起来像是从QObject
继承的(的QObject::startTimer和QOobject::timerEvent方法,如下所示:
void client::initConnection(){
connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readMessage()));
connect(tcpSocket, SIGNAL(connected()), this, SLOT(clientConnected()));
connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(disconnectedFromHost()));
// checkConnectionTimerId - is a member of class `client`
checkConnectionTimerId = startTimer(1000);
}
void client::timerEvent(QTimerEvent *event)
{
if (event->timerId() == checkConnectionTimerId) {
if (tcpSocket->state() != QAbstractSocket::ConnectedState) {
tcpSocket->connectToHost(address, port, QIODevice::ReadWrite);
}
}
}
相关文章:
- QTcpSocket在不阻塞GUI的情况下重新连接到服务器
- 在不知道套接字的情况下关闭网络连接
- 在没有管理员权限的情况下连接到同一网络中的命名管道
- (Windows 10) 在不更新的情况下重新启动C++
- 如何在不退出和失去断点的情况下重新加载重新编译的二进制文件
- 是否可以在不使用"undef"的情况下重新定义宏?
- 在没有互斥锁的情况下重新计数时如何避免竞争条件?
- 在没有额外成员的情况下重新解释转换为派生类可以吗
- Eclipse CDT:如何在没有项目清理>>项目重建的情况下重新链接静态库
- RCpp:如何在不重新启动R的情况下重新加载重新编译的C++代码
- 我可以在不重新连接的情况下多次使用BIO_puts、BIO_read吗
- std::string和const char情况下的连接优先级
- 有没有一种方法可以在不重建任何项目的情况下重新链接解决方案
- 如何在没有终结器的情况下重新编译WinSCP
- 如何让火狐在不重新启动的情况下重新加载user_pref
- 如何在不影响 ALT+F4 或在任务栏中关闭窗口的情况下重新调整窗口关闭按钮的用途?
- 我们如何在不杀死线程的情况下重新初始化线程
- 如何在没有延迟的情况下重新定位窗口中的图形
- 如何在不将字符串对象嵌入自定义异常类的情况下重新格式化错误消息
- Mac GUI应用程序如何在不使用Sparkle的情况下重新启动自己?