当前位置:   article > 正文

Qt QTcpSocket 客户端设计(自动重连、多线程处理、发送大数据包、同步方式)

qtcpsocket

1.头文件

#ifndef TCPTOOL_H
#define TCPTOOL_H

#include <QObject>
#include <QTcpSocket>
#include <QHostAddress>

class TCPTool : public QObject
{
    Q_OBJECT
    //单例模式
private:
    TCPTool();
public:
    static TCPTool * GetInstance()
    {
        static TCPTool instance;
        return &instance;
    }
    ~TCPTool();

	//变量
private:
    bool m_exitThread;
    QTcpSocket * m_tcpClient;
    bool m_isConnected;

    //函数
public:
	bool SendLargeData(QByteArray & block);
	
private:
    void ProcessThread();
    bool Connect(const QString & address,int port);

signals:
    void TryConnectSignal();

public slots:
    void Disconnected();
    void ReadMessage();
    void TryConnectSlot();
};

#endif // TCPTOOL_H

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46

2.源代码

#include "tcptool.h"
#include <thread>
#include "setting.h"//设置头文件

TCPTool::TCPTool()
{
    m_tcpClient = new QTcpSocket(this);
    m_tcpClient->abort();//取消原有连接

    connect(this,SIGNAL(TryConnectSignal()),this,SLOT(TryConnectSlot()));
    connect(m_tcpClient,SIGNAL(readyRead()),this,SLOT(ReadMessage()));
    connect(m_tcpClient,SIGNAL(disconnected()),this,SLOT(Disconnected()));

    m_isConnected = false;
    m_exitThread = false;

    std::thread sendThread(&TCPTool::ProcessThread,this);
    sendThread.detach();
}

TCPTool::~TCPTool()
{
    Disconnected();
    m_exitThread = true;
}

bool TCPTool::SendLargeData(QByteArray & block)
{
	if(!m_isConnected)
		return false;
    //分包发送
    const int PayloadSize = 64*1024;//一个帧数据包大小
    int totalSize = block.size();
    int bytesWritten = 0;
    int bytesToWrite = totalSize;
    while(bytesWritten<totalSize)
    {
        int startIdx = bytesWritten;
        int length = std::min(PayloadSize,bytesToWrite);
        if(startIdx+length>totalSize)
            return false;

        QByteArray smallBlock = block.mid(startIdx,length);
        qint64 written = m_tcpClient->write(smallBlock);
        bool success = m_tcpClient->waitForBytesWritten();

        if(!success)//发送失败包时,停止发送
            return false;

        bytesWritten+=written;
        bytesToWrite-=written;
    }
    m_tcpClient->flush();

    return true;
}

void TCPTool::ProcessThread()
{
    while(m_exitThread==false)
    {
    	//重连尝试
        if(!m_isConnected)
        {
            emit TryConnectSignal();
            usleep(200000);//等待连接尝试

            if(!m_isConnected)
            {
                usleep(5000000);//等待5秒重连
                continue;
            }
        }

		//执行发送(未展开,思路:大块数据从队列读出,然后在线程中执行同步发送)
		//SendLargeData(data);
		
        usleep(1000000);//等待1s
    }
}

bool TCPTool::Connect(const QString & address, int port)
{
    if(!m_tcpClient)
    {
        m_isConnected = false;
        return false;
    }

    //直接读取状态,如果连接正常,则直接返回
    if(m_tcpClient->state()== QAbstractSocket::ConnectedState)
    {
        if(m_tcpClient->isValid())
        {
            m_isConnected = true;
            return true;
        }
        else
        {
            m_isConnected = false;
            return false;
        }
    }

    //尝试连接
    m_tcpClient->abort();//取消原有连接
    m_tcpClient->connectToHost(address,port);
    if(m_tcpClient->waitForConnected(1000))
    {
        m_isConnected = true;
    }
    else
        m_isConnected = false;
    return m_isConnected;
}

void TCPTool::Disconnected()
{
    m_isConnected = false;
    if(!m_tcpClient)
        return;

    if(m_tcpClient->state()== QAbstractSocket::UnconnectedState||m_tcpClient->waitForDisconnected(1000))
        return;
}

void TCPTool::ReadMessage()
{
    QByteArray buf = m_tcpClient->readAll();//读取数据
}

void TCPTool::TryConnectSlot()
{
    Connect(Setting_Server_IPAddress,Setting_Server_IPPort);
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136

3.说明

3.1.自动重连

使用waitForConnected时会有等待时间,如果放在主线程中,会造成卡顿。定时器也不能执行等待(一般情况定时器运行在主线程),因此选择在线程中执行重复连接。

注意:如果在线程中执行Connect函数时,会引起:

QObject: Cannot create children for a parent that is in a different thread. (Parent is QTcpSocket(0x142f1860), parent’s thread is QThread(0xbbac10), current thread is QThread(0x7fff18001040)
QObject::startTimer: Timers can only be used with threads started with QThread QObject: Cannot create children for a parent that is in a different thread. (Parent is QTcpSocket(0x142f1860), parent’s thread is QThread(0xbbac10), current thread is QThread(0x7fff18001040)

经测试,在线程中调用connectToHost会引起如上问题。使得发送、接收信号都停留在子线程中,只有当子线程exec()之后才释放信号,从而引起接收不到信息(未触发readyRead)和发送不出去信息(write后没有立即发送出去)
因此代码中使用信号、槽执行重新连接尝试。发送信号后,等待片刻读取执行结果。详见代码中示例。

3.2.发送大数据包

执行write()时,只能发送一个小的数据包(与系统相关),大的数据包需要进行拆分才能进行发送。本文中在线程中使用同步方式发送大数据包,在线程中write()waitForBytesWritten()配合即可完成同步方式发送。

以上代码经测试基本功能完善,仅供参考。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/187373
推荐阅读
相关标签
  

闽ICP备14008679号