网络|QTcpSocket断开后自动重连问题 auto connect after disconnected

class SocketThread : public QThread { Q_OBJECTpublic://public functions SocketThread(QObject *parent); ~SocketThread(); void run(); public://public variables QTcpSocket* m_pTcpSocket; bool m_bServerConnected; QTimer m_timer; public slots: void OnSocketError(QAbstractSocket::SocketError); void OnSocketConnected(); void OnSocketDisconnected(); void ConnectServer(); signals: void ShowStatus(QString str); private:};

#include "socketthread.h"SocketThread::SocketThread(QObject *parent) : QThread(parent) { m_bServerConnected = false; m_pTcpSocket = new QTcpSocket; connect(m_pTcpSocket, SIGNAL(connected()), this, SLOT(OnSocketConnected())); connect(m_pTcpSocket, SIGNAL(disconnected()), this, SLOT(OnSocketDisconnected())); connect(m_pTcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(OnSocketError(QAbstractSocket::SocketError))); connect(&m_timer, SIGNAL(timeout()), this, SLOT(ConnectServer())); m_timer.setInterval(3000); m_timer.start(); moveToThread(this); //must be the last executed}SocketThread::~SocketThread() {}void SocketThread::run() { this->exec(); }void SocketThread::OnSocketConnected() { emit ShowStatus("Server connected"); m_bServerConnected = true; }void SocketThread::OnSocketDisconnected() { emit ShowStatus("Server disconnected"); m_bServerConnected = false; }void SocketThread::OnSocketError(QAbstractSocket::SocketError error) { emit ShowStatus(m_pTcpSocket->errorString()); }void SocketThread::ConnectServer() { if(!m_bServerConnected) { m_pTcpSocket->connectToHost("192.168.2.1", 8745); //m_pTcpSocket->waitForConnected(2000); //如果调用这句,界面会卡死 } }


几个比较麻烦的问题:
【网络|QTcpSocket断开后自动重连问题 auto connect after disconnected】1.线程signal不响应,这是因为需要调用exec()进入消息循环。不过调用exec()就会进入一直等待的循环中,因此exec()必须在run函数中调用。这样就导致无法使用循环的方式connectToHost,如果在OnSocketDisconnected()中进行循环connect就会导致一直占用线程,界面卡死。因此,最理想的是使用Timer进行控制。
2.moveToThread(this),这句话具体应该怎么用还有待进一步查阅资料。如果不调用这句可能会出现线程中调用了不是该线程创建的对象错误。在该类初始化时会有socket实例化,如果定义了SocketThread变量,那么socket是在定义SocketThread变量中实例化的。也就是说,该socket对象是由调用线程创建的而不是SocketThread创建的。从而导致错误。
3.waitForConnected()这句也会出现等待,如果调用这句就会出现界面卡死的问题。




    推荐阅读