tcpSocket->connectToHost(host,port);
class Client : public QWidget{ Q_OBJECTprivate: QLineEdit* txtInput; quint16 nextBlockSize; QTextEdit* txtInfo; MyThread* timerThread;public: Client(const QString& strHost, int nPort, QWidget *parent = 0, Qt::WFlags flags = 0); QString host; int port; QTcpSocket* tcpSocket;private slots: void slotReadyRead (); void slotError (QAbstractSocket::SocketError); void slotSendToServer(); void slotConnected();};
class MyThread : public QThread{ Q_OBJECTpublic: MyThread(QObject *parent); void run(Client* client); void stop(); bool getStopped(); void setStoppedToFalse();private: QTimer* tcpTimer; volatile bool stopped; volatile bool timerExist;private slots: void slotConnectToHost(Client *some_client);};
void MyThread::slotConnectToHost(Client *some_client){ some_client->tcpSocket->connectToHost(some_client->host,some_client->port); if (some_client->tcpSocket->waitForConnected()) this->stop();}
void MyThread::run(Client* client){ if (!stopped) { qDebug() << "Thread RUN"; if (!timerExist) { tcpTimer = new QTimer(this); connect(tcpTimer, SIGNAL(timeout()), SLOT(slotConnectToHost(client))); timerExist = true; } tcpTimer->start(5000); }}
Client::Client(const QString& strHost, int nPort, QWidget *parent, Qt::WFlags flags) : QWidget(parent, flags), nextBlockSize(0){ // создаем GUI txtInfo = new QTextEdit; txtInput = new QLineEdit; txtInfo->setReadOnly(true); QPushButton* pcmd = new QPushButton("Send"); QVBoxLayout* pvbxLayout = new QVBoxLayout; pvbxLayout->addWidget(new QLabel("<H1>Client</H1>")); pvbxLayout->addWidget(txtInfo); pvbxLayout->addWidget(txtInput); pvbxLayout->addWidget(pcmd); setLayout(pvbxLayout); host = strHost; port = nPort; // создаем сокет и создаем поток, который отвечает за коннект сокета к серверу tcpSocket = new QTcpSocket(this); timerThread = new MyThread(this, this); timerThread->run(); connect(tcpSocket, SIGNAL(connected()), SLOT(slotConnected())); connect(tcpSocket, SIGNAL(readyRead()), SLOT(slotReadyRead())); connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(slotError(QAbstractSocket::SocketError))); connect(pcmd, SIGNAL(clicked()), SLOT(slotSendToServer())); connect(txtInput, SIGNAL(returnPressed()), this, SLOT(slotSendToServer()));}void Client::slotReadyRead(){ // неважно}void Client::slotError(QAbstractSocket::SocketError err){ QTime time; QSqlQuery query; query.prepare("INSERT INTO client (Time, Event, Code) VALUES (:time, 'Error', :code);"); query.bindValue(":time",time.currentTime().toString()); QString strError = time.currentTime().toString() + " Error: "; if (err==QAbstractSocket::HostNotFoundError) { strError = strError + "The host was not found"; query.bindValue(":code","The host was not found"); } else if (err==QAbstractSocket::RemoteHostClosedError) { strError = strError + "The remote host is closed"; query.bindValue(":code","The remote host is closed"); } else if (err==QAbstractSocket::ConnectionRefusedError) { strError = strError + "The Connection was refused"; query.bindValue(":code","The Connection was refused"); } else { strError = strError + tcpSocket->errorString(); query.bindValue(":code",tcpSocket->errorString()); } query.exec(); txtInfo->append(strError); // при возникновении ошибки (например когда сервер не запущен), если поток в данный момент не занят подключением (такая ситуация возникает если сервер был открыт и вдруг закрылся), вновь создать поток, который начнет искать подключение if (timerThread->getStopped()) { timerThread = new MyThread(this, this); timerThread->run(); }}void Client::slotSendToServer(){ // неважно}void Client::slotConnected(){ QTime time; QString mess = time.currentTime().toString()+" Received the connected signal"; txtInfo->append(mess); QSqlQuery query; query.prepare("INSERT INTO client (Time, Event, Code) VALUES (:time, 'General', 'Received the connected signal');"); query.bindValue(":time",time.currentTime().toString()); query.exec();}
MyThread::MyThread(QObject *parent, Client *some_client) : QThread(parent){ qDebug() << "New Thread"; temp_client = some_client; stopped = false; timerExist = false;}void MyThread::setStoppedToFalse(){ stopped = false;}bool MyThread::getStopped(){ return stopped;}void MyThread::run(){ if (!stopped) { qDebug() << "Thread RUN"; if (!timerExist) { tcpTimer = new QTimer(this); connect(tcpTimer, SIGNAL(timeout()), SLOT(slotConnectToHost())); timerExist = true; } tcpTimer->start(5000); }}void MyThread::stop(){ qDebug() << "Thread STOP"; tcpTimer->stop(); stopped=true;}void MyThread::slotConnectToHost(){ temp_client->tcpSocket->connectToHost(temp_client->host,temp_client->port); if (temp_client->tcpSocket->waitForConnected()) this->stop();}
static bool createConnection(){ QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL"); db.setHostName("localhost"); db.setDatabaseName("test"); db.setUserName("root"); db.setPassword("root"); if (!db.open()) { qDebug() << "Cannot open database: " << db.lastError(); return false; } else qDebug() << "Open database OK"; return true;}int main(int argc, char *argv[]){ QApplication app(argc, argv); QFile file("config.xml"); QXmlInputSource source(&file); QXmlSimpleReader reader; SaxHandler handler; reader.setContentHandler(&handler); reader.parse(source); if (!createConnection()) return -1; Client client(handler.hostName, handler.portNumber); client.show(); return app.exec();}
void QObject::moveToThread ( QThread * targetThread )