主线程最后必须调用exit()和wait()函数
源码地址 http://download.csdn.net/download/u010261063/10185891
#ifndef QSYSENDTHREAD_H
#define QSYSENDTHREAD_H
#include <QThread>
#include<QTcpSocket>
#include<common.h>
#include<QTimer>
class QSYSendThread : public QThread
{
Q_OBJECT
public:
explicit QSYSendThread(QObject *parent = 0);
signals:
public slots:
void ClientClosed();
void ClientError(QAbstractSocket::SocketError socketError);
void TimeOut();
public:
void run();
private:
QTcpSocket *m_client;
QString m_conectIP;
bool m_bconnect;
uint m_connectPort;
QTimer *m_pTimer;
};
#endif // QSYSENDTHREAD_H
源文件
#ifndef QSYSENDTHREAD_H
#define QSYSENDTHREAD_H
#include <QThread>
#include<QTcpSocket>
#include<common.h>
#include<QTimer>
class QSYSendThread : public QThread
{
Q_OBJECT
public:
explicit QSYSendThread(QObject *parent = 0);
signals:
public slots:
void ClientClosed();
void ClientError(QAbstractSocket::SocketError socketError);
void TimeOut();
public:
void run();
private:
QTcpSocket *m_client;
QString m_conectIP;
bool m_bconnect;
uint m_connectPort;
QTimer *m_pTimer;
};
#endif // QSYSENDTHREAD_H
源文件
#include "qsysendthread.h"
QSYSendThread::QSYSendThread(QObject *parent) : QThread(parent)
{
}
void QSYSendThread::run()
{
m_conectIP = g_EnvVariant.m_conectToIp;
m_connectPort = g_EnvVariant.m_conectToPort;
m_client = new QTcpSocket();
m_client->connectToHost(m_conectIP,m_connectPort);
connect(m_client,QTcpSocket::disconnected,this,QSYSendThread::ClientClosed,Qt::DirectConnection);
connect(m_client,QTcpSocket::readyRead,this,QSYSendThread::ClientClosed,Qt::DirectConnection);
if(m_client->state()==QAbstractSocket::ConnectedState)
{
cout<<"connnect to server fail !!! ";
}
else
{
cout<<"connnect to server successful !!! ";
}
m_pTimer = new QTimer();
m_pTimer->start(2000);
connect(m_pTimer,QTimer::timeout,this,QSYSendThread::TimeOut,Qt::DirectConnection);
exec();
delete m_client;
delete m_pTimer;
}
void QSYSendThread::ClientClosed()
{
cout<<"server is closed !!! ";
}
void QSYSendThread::ClientError(QAbstractSocket::SocketError /*socketError*/)
{
}
void QSYSendThread::TimeOut()
{
if(m_client->state()==QAbstractSocket::UnconnectedState)
{
m_client->connectToHost(m_conectIP,m_connectPort);
cout<<"connnect to server !!! ";
}
cout<<"timeout!! ";
}