Files

121 lines
2.9 KiB
C++
Raw Permalink Normal View History

#include "TcpThread.h"
TcpThread::TcpThread(qintptr socketDecriptor, QObject* parent) : QThread(parent)
{
m_ip = NULL;
m_port = 0;
m_socketDescriptor = socketDecriptor;
m_socket = nullptr;
}
TcpThread::TcpThread(QHostAddress ip, quint16 port, QObject* parent) : QThread(parent)
{
m_ip = ip;
m_port = port;
m_socketDescriptor = 0;
m_socket = nullptr;
}
TcpThread::~TcpThread()
{
//qDebug() << "[线程] -> 析构开始";
if (m_socket) {
//qDebug() << "[线程] -> 释放socket";
m_socket->disconnect(); // 断开所有信号
m_socket->abort(); // 强制断开连接
m_socket->deleteLater(); // 延迟删除
m_socket = nullptr;
}
//qDebug() << "[线程] -> 析构完成";
}
void TcpThread::run()
{
if (!m_socket)
{
m_socket = new TcpSocket();
}
if (m_socketDescriptor)
{
//qDebug() << "客户端设置:" << m_socketDescriptor;
if (!m_socket->setSocketDescriptor(m_socketDescriptor))
{
qDebug() << "设置失败";
return;
}
}
// 数据到达
connect(m_socket, &TcpSocket::signalDataRecv, this, &TcpThread::slotDataRecv, Qt::QueuedConnection);
// 连接建立
connect(m_socket, &TcpSocket::connected, this, &TcpThread::slotConnected, Qt::QueuedConnection);
// 连接断开
connect(m_socket, &TcpSocket::disconnected, this, &TcpThread::slotDisconnected, Qt::QueuedConnection);
// 数据发送
connect(this, &TcpThread::signalSendData, m_socket, &TcpSocket::slotSendData, Qt::QueuedConnection);
if (!m_ip.isNull() && m_port)
{
//qDebug() << "连接";
m_socket->connectToHost(m_ip, m_port);
m_socket->waitForConnected(1000);
}
this->exec();
// 线程退出时安全释放socket
if (m_socket) {
// qDebug() << "[线程] -> 退出时释放socket";
m_socket->abort();
m_socket->disconnect();
m_socket->deleteLater();
m_socket = nullptr;
}
//qDebug() << "线程退出";
}
void TcpThread::slotSendData(qintptr socketDescriptor, QByteArray data)
{
//qDebug() << "[线程] -> 发送数据";
if (socketDescriptor != this->m_socketDescriptor)
{
return;
}
if (data.isEmpty())
{
//qDebug() << "数据发送:数据为空";
return;
}
emit this->signalSendData(data);
}
void TcpThread::slotDataRecv(qintptr socketDescriptor, QByteArray data)
{
//qDebug() << "[线程] -> 接收数据";
if (data.isEmpty())
{
//qDebug() << "数据接收:数据为空";
return;
}
emit this->signalDataRecv(socketDescriptor, data);
}
void TcpThread::slotConnected()
{
//qDebug() << "[线程] -> 连接:" << m_socket->socketDescriptor();
m_socketDescriptor = m_socket->socketDescriptor();
emit signalConnected(m_socketDescriptor);
}
void TcpThread::slotDisconnected()
{
//qDebug() << "[线程] -> 断开:" << m_socketDescriptor;
emit signalDisconnected(m_socketDescriptor);
}