天天看點

QT 自定義Socket消息類,并進行運算符重載

  • TCP通信需要自定義消息體,本博文是建構了一個QT下的消息類。

.h

// 消息結構體,消息頭為20個位元組
typedef struct
{
    unsigned int send_id;       // 發送方的ID(網絡的IP、SRIO的ID)
    unsigned int recv_id;       // 接收方的ID(網絡的IP、SRIO的ID)
    unsigned int msg_type : 8;  // 消息類型
    unsigned int len : 24;      // 消息長度,位元組數
    unsigned int conn_type: 8;  // 連接配接類型,TCP、UDP等
    unsigned int pkg_num : 8;   // 總的包數(用于組包傳輸)
    unsigned int pkg_idx : 8;   // 子包索引(用于組包傳輸),從1計數
    unsigned int rsvd : 8;      // 保留位
    unsigned int check_sum;     // 校驗位
} DispCtrlMsg;
           
#ifndef MESSAG_H
#define MESSAG_H
#include "msg_type.h"
#include <QByteArray>
#include <iostream>

class Messag
{

private:
    DispCtrlMsg *msgHead;
    QByteArray *msgBody;
public:
    explicit Messag();
    ~Messag();

    void saveMsgHead(const DispCtrlMsg &head);
    void saveMsgBody(const QByteArray &body);
    const DispCtrlMsg& getMsgHead(void);
    const QByteArray& getMsgBody(void);

    Messag &operator=(Messag *pre);

};

#endif // MESSAG_H

           

.c

#include "messag.h"


Messag::Messag()
{
    msgHead = new DispCtrlMsg();
    msgBody = new QByteArray();
}


Messag::~Messag()
{
    delete msgHead;
    delete msgBody;
}

void Messag::saveMsgHead(const DispCtrlMsg &head)
{
    msgHead->check_sum = head.check_sum;
    msgHead->conn_type = head.conn_type;
    msgHead->len = head.len;
    msgHead->load = head.load;
    msgHead->msg_type = head.msg_type;
    msgHead->pkg_idx = head.pkg_idx;
    msgHead->pkg_num = head.pkg_num;
    msgHead->recv_id = head.recv_id;
    msgHead->rsvd = head.rsvd;
    msgHead->send_id = head.send_id;
}
void Messag::saveMsgBody(const QByteArray &body)
{
    *msgBody = body;
}

const DispCtrlMsg& Messag::getMsgHead(void)
{
    return *msgHead;
}

const QByteArray& Messag::getMsgBody(void)
{
    return *msgBody;
}

Messag &Messag::operator=(Messag *pre)
{
    this->saveMsgHead(pre->getMsgHead());
    this->saveMsgBody(pre->getMsgBody());
}
           
  • 運算符重載:指派運算符重載,傳回Message的引用,使用關鍵字 operator,使用智能指針,this.

繼續閱讀