数据消息至少8个字符可通过计算数据消息的总长度,能够避开数据粘粘问题
实现功能如下
将协议对象组装成一个完整的字符串类型的消息将一个满足协议规则的字符串装配成一个协议对象详见main函数测试TextMessage.pro
QT -= gui CONFIG += c++11 console CONFIG -= app_bundle # The following define makes your compiler emit warnings if you use # any feature of Qt which as been marked deprecated (the exact warnings # depend on your compiler). Please consult the documentation of the # deprecated API in order to know how to port your code away from it. DEFINES += QT_DEPRECATED_WARNINGS # You can also make your code fail to compile if you use deprecated APIs. # In order to do so, uncomment the following line. # You can also select to disable deprecated APIs only up to a certain version of Qt. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 SOURCES += main.cpp \ textmessage.cpp HEADERS += \ textmessage.h
textmessage.h
#ifndef TEXTMESSAGE_H #define TEXTMESSAGE_H #include <QObject> class TextMessage : public QObject { Q_OBJECT QString m_type; QString m_data; public: explicit TextMessage(QObject *parent = nullptr); TextMessage(QString type, QString data, QObject* parent = NULL); QString type(); int length(); QString data(); QString serialize(); bool unserialize(QString s); signals: public slots: }; #endif // TEXTMESSAGE_Htextmessage.cpp
#include "textmessage.h" TextMessage::TextMessage(QObject *parent) : QObject(parent) { m_data=""; m_type=""; } TextMessage::TextMessage(QString type, QString data, QObject* parent):QObject(parent) { m_type=type.trimmed(); m_type.resize(4,' '); m_data=data.mid(0,0xFFFF); } QString TextMessage::type() { return m_type; } int TextMessage::length() { return m_data.length(); } QString TextMessage::data() { return m_data; } QString TextMessage::serialize() { QString len=QString::asprintf("%X", m_data.length()); len.resize(4,' '); return m_type+len+m_data; } bool TextMessage::unserialize(QString s) { bool ret=(s.length()>=8); if(ret) { QString type=s.mid(0,4); QString len=s.mid(4,4); int length=len.toInt(&ret,16); ret=ret&&( (s.length()-8)==length); if(ret) { m_type=type; m_data=s.mid(8,length); } } return ret; }main.cpp
#include <QCoreApplication> #include <QDebug> #include "textmessage.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); TextMessage tm("AB","1234567890"); QString message=tm.serialize(); qDebug()<<message; TextMessage tmt; tmt.unserialize(message); qDebug()<<tmt.type(); qDebug()<<tmt.length(); qDebug()<<tmt.data(); return a.exec(); }结果