Qt 网络发送带中文字符串

数据封装

#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif
#ifndef PROTOCOL_H
#define PROTOCOL_H

#include
#include
#include
#include 
#include 
#include 
#include

 #pragma pack(1)
    typedef struct{
         uchar head[8]={0x7d,0x7b,
                        0x02,//目标地址长度
                        0x00,0x01,//目标地址
                        0x02,//源地址长度
                        0x10,0x00,//源地址
                       };
         uchar cmd;//命令
         uchar Extension;//拓展码
         uchar len[2];
         char msg_data[0];
     }ALARM_INFO_PAGE;  // 报警信息
#pragma pack()

public:
    Protocol();
    char* MsgPagetoChar();  
    int MsgPageSize();
    ALARM_INFO_PAGE  AlarmInfoPage;
};
#endif // PROTOCOL_H

#include "protocol.h"
#include"string.h"
#include"cstring"
#include
#include
//枚举的读写,可以用枚举的方式来说明所打的包是给谁运行的

Protocol::Protocol()
{
    this->clear();
}
void P
char* Protocol::MsgPagetoChar()
{
    return reinterpret_cast<char*>(&(this->AlarmInfoPage));
}
int Protocol::MsgPageSize()
{
    return sizeof(AlarmInfoPage);
}

数据发送


void SocketInterface::onConnected()
{
    QByteArray byteArr="试剂,那么多达克宁!";
    Protocol p;
    p.AlarmInfoPage.cmd=0x88;
    p.AlarmInfoPage.Extension=0x99;

    Protocol::ALARM_INFO_PAGE *pMsgPage = (Protocol::ALARM_INFO_PAGE *)malloc(sizeof(p.AlarmInfoPage) + byteArr.size()+4);
  
    memcpy(pMsgPage->msg_data,byteArr.data(),byteArr.size());
    //设置CRC 与帧尾
    pMsgPage->msg_data[byteArr.size()+0]=0xCC;
    pMsgPage->msg_data[byteArr.size()+1]=0xCC;
    pMsgPage->msg_data[byteArr.size()+2]=0x7D;
    pMsgPage->msg_data[byteArr.size()+3]=0x7D;
    
    uchar len[2]={0x00,0x30}; //包长
    len[1]=byteArr.size();
    memcpy(p.AlarmInfoPage.len,len,sizeof(char)*2);  /数据长度

    QByteArray *page=new QByteArray(p.MsgPagetoChar(),p.MsgPageSize()+byteArr.size()+4);
    memcpy(page->data()+p.MsgPageSize(),pMsgPage->msg_data,byteArr.size()+4);
    
    socket->write(page->data(),page->size());

}

数据接收:

void ExTcpServer::onSocketReadyRead()     //读取缓冲区行文本
{
    QByteArray strbuf=m_tcpSocket->readAll();
    qDebug()<<"FIAService::ReadData:"<<strbuf.toHex().toUpper();

    QTextCodec *codeDest = QTextCodec::codecForName("UTF-8");
    QString strDest = codeDest->toUnicode(strbuf);
    ushort dataLen=strbuf.mid(10,2).toHex().toShort(nullptr,16);  //获取数据长度
    QString strShow =codeDest->toUnicode(strbuf.mid(12,dataLen));
    qDebug()<<"-------------"<<strShow <<endl;
}

你可能感兴趣的:(qt,qt,网络,开发语言)