写一个在x线程中管理的tcp
#include <QThread> #include <QTcpSocket> #include <QObject> #include <QNetworkProxy> class TcpSocketController : public QTcpSocket { Q_OBJECT public: TcpSocketController(QObject* parent = nullptr) : QTcpSocket(parent) { connect(this, &TcpSocketController::readyRead, this, &TcpSocketController::onInCommingData); connect(this, &TcpSocketController::signal_SendData, this, &TcpSocketController::OnSendData); } ~TcpSocketController() {} signals: void signal_ReadData(const QByteArray& d); void signal_SendData(const QByteArray& d); public slots: void OnSendData(const QByteArray& d) { qint64 len = write(d); } void onInCommingData() { QByteArray data = readAll(); if (data.length() > 0) { emit signal_ReadData(data); } } }; /* 使用方式: TcpSocketEx 创建一个对象 InitTcp(QString ip, int port)初始化链接 WriteData(QByteArray d)发送tcp数据 signal_ReadData(const QByteArray&) 信号曹返回tcp数据 ****************************/ class TcpSocketEx : public QObject { Q_OBJECT public: TcpSocketEx(QObject* parent = nullptr) : QObject(parent) { m_tcp_client = new TcpSocketController; } ~TcpSocketEx() { if (workerThread.isRunning()) { workerThread.quit(); workerThread.wait(); } } bool InitTcp(QString ip, int port) { m_tcp_client->setProxy(QNetworkProxy::NoProxy); m_tcp_client->connectToHost(QHostAddress(ip), port); if (!m_tcp_client->waitForConnected(3000)) { // connection failed qDebug() << "connection failed " << ip << ":" << port; m_isConnect = false; return false; } // connection success m_tcp_client->moveToThread(&workerThread); connect(&workerThread, &QThread::finished, m_tcp_client, &QObject::deleteLater); connect(m_tcp_client, &TcpSocketController::signal_ReadData, this, &TcpSocketEx::signal_ReadData, Qt::DirectConnection); connect(m_tcp_client, &TcpSocketController::connected, this, [=]() { m_isConnect = true; emit signal_connected(); }); connect(m_tcp_client, &TcpSocketController::disconnected, this, [=]() { m_isConnect = false; emit signal_disconnected(); }); connect(m_tcp_client, &TcpSocketController::stateChanged, this, &TcpSocketEx::signal_stateChanged); workerThread.start(); m_isConnect = true; return true; } void WriteData(QByteArray d) { emit m_tcp_client->signal_SendData(d); } void WriteData(QString d) { WriteData(d.toLatin1()); } // 链接状态 bool isConnect() { return m_isConnect; } signals: void signal_ReadData(const QByteArray& d); // 接受数据信号 void signal_connected(); // 信号 void signal_disconnected(); // 信号 void signal_stateChanged(QAbstractSocket::SocketState); private: QThread workerThread; TcpSocketController* m_tcp_client = nullptr; bool m_isConnect = false; };
标签:QByteArray,qt,signal,tcp,client,线程,TcpSocketController,void From: https://www.cnblogs.com/dwx-bzdcxy/p/18212223