qt 心跳设计

 网络通信中的心跳设计是为了判断客户端和服务器通信是socket是否处于连接状态,服务端每隔一个固定的时间间隔给客户端放消息,客户端设计一个心跳类,类中有一个定时器,当socket接收到信息时,心跳类记录接到消息时的时间,然后判断在固定时间间隔内有没有接收到服务器端发来的信息,然后没有收到可以判断网络连接已经断开。

心跳类:

class HeartBeat : public QObject

{
    Q_OBJECT
public:
    HeartBeat(QObject *parent, int interval)
        : QObject(parent)
    {
        checkTimer = new QTimer(this);
        checkTimer->setInterval(interval);
        last = QDateTime::currentDateTime();
        connect(checkTimer, SIGNAL(timeout()), 
                this, SLOT(check()));
    }

    ~HeartBeat() { delete checkTimer; }
    void beat()
    {
        if (!checkTimer->isActive())
            checkTimer->start();
        last = QDateTime::currentDateTime();
    }
signals:
    void dead();
private slots:
    void check()
    {
        if (last.secsTo(QDateTime::currentDateTime()) >= 30) {
            checkTimer->stop();
            emit dead();
        }
    }

private:
    QDateTime  last;
    QTimer*    checkTimer;
};

服务器端发送心跳的方法各异,都是往socket中定时发送消息就可以
客户端:
    socket = new StringTcpSocket(this);
    connect(socket, SIGNAL(dataRead(QString)), 
            this,   SLOT(onDataRead(QString)));

    heart = new HeartBeat(this, 30000);
    connect(heart, SIGNAL(dead()), this, SLOT(onDead()));


onDead 函数中做一些网络已经断开后,数据的处理。
然后在socket发送dataRead() 信号时的slot函数onDataRead() 函数中加入
heart->beat();

http://www.cnblogs.com/thorngirl/articles/3927914.html

原文地址:https://www.cnblogs.com/findumars/p/6142803.html