16,173
社区成员
发帖
与我相关
我的任务
分享
#ifndef MYTCPSOCKET_H
#define MYTCPSOCKET_H
#include <QTcpSocket>
#include <QThread>
#include <QDebug>
#include <QHostAddress>
class MyTcpSocket : public QThread
{
Q_OBJECT
public:
MyTcpSocket()
: m_pQTcpSocket(new QTcpSocket())
{
this->start();
this->moveToThread(this);
m_pQTcpSocket->moveToThread(this);
connect(this, SIGNAL(DoMyWrite(QByteArray)),
this, SLOT(OnMyWrite(QByteArray)));
connect(this, SIGNAL(DoMyConnect()),
this, SLOT(OnMyConnectToHost()));
}
~MyTcpSocket()
{
this->exit();
this->wait(10 * 1000);
}
void myWrite(const char *data, qint64 len)
{
emit DoMyWrite(QByteArray(data, len));
}
void myConnectToHost()
{
emit DoMyConnect();
}
signals:
void DoMyWrite(const QByteArray &data);
void DoMyConnect();
private slots:
void OnMyWrite(const QByteArray &data)
{
qDebug() << "write" << QThread::currentThreadId();
m_pQTcpSocket->write(data);
m_pQTcpSocket->flush();
}
void OnMyConnectToHost()
{
qDebug() << "myConnect" << QThread::currentThreadId();
m_pQTcpSocket->connectToHost(QHostAddress::LocalHost, 8811);
}
private:
QTcpSocket * const m_pQTcpSocket;
};
#endif // MYTCPSOCKET_H
[/quote]
谢谢,改用定时器确实不会有这问题了。
#ifndef MYTCPSOCKET_H
#define MYTCPSOCKET_H
#include <QTcpSocket>
#include <QThread>
#include <QDebug>
#include <QHostAddress>
class MyTcpSocket : public QThread
{
Q_OBJECT
public:
MyTcpSocket()
: m_pQTcpSocket(new QTcpSocket())
{
this->start();
this->moveToThread(this);
m_pQTcpSocket->moveToThread(this);
connect(this, SIGNAL(DoMyWrite(QByteArray)),
this, SLOT(OnMyWrite(QByteArray)));
connect(this, SIGNAL(DoMyConnect()),
this, SLOT(OnMyConnectToHost()));
}
~MyTcpSocket()
{
this->exit();
this->wait(10 * 1000);
}
void myWrite(const char *data, qint64 len)
{
emit DoMyWrite(QByteArray(data, len));
}
void myConnectToHost()
{
emit DoMyConnect();
}
signals:
void DoMyWrite(const QByteArray &data);
void DoMyConnect();
private slots:
void OnMyWrite(const QByteArray &data)
{
qDebug() << "write" << QThread::currentThreadId();
m_pQTcpSocket->write(data);
m_pQTcpSocket->flush();
}
void OnMyConnectToHost()
{
qDebug() << "myConnect" << QThread::currentThreadId();
m_pQTcpSocket->connectToHost(QHostAddress::LocalHost, 8811);
}
private:
QTcpSocket * const m_pQTcpSocket;
};
#endif // MYTCPSOCKET_H
QTcpSocket* g_tcpSocket = new QTcpSocket();
HANDLE g_handleHeartBeat = CreateThread(NULL, 0, RunHeartBeat, g_Client, 0, NULL); // 创建心跳线程
DWORD WINAPI RunHeartBeat(LPVOID param)
{
WaitForSingleObject(g_hMutex, INFINITE);
Request request; // 需要向服务端发送的内容
//.....填写request
int nleft, nbytes;
char* ptr = (char*)&request;
nleft = 12; // 需要发送的长度
for (; nleft > 0; )
{
nbytes = g_tcpSocket->write(ptr, nleft);
g_tcpSocket->flush(); // 注释掉这行以后release版本就稳定了,但是debug版本不会及时发出消息
if (nbytes <= 0)
{
// .......
ReleaseMutex(g_hMutex);
return -1;
}
nleft -= nbytes;
ptr += nbytes;
}
ReleaseMutex(g_hMutex);
}
主线程基本是一样的代码。能帮忙看一下吗,多谢!