多语言展示
当前在线:1667今日阅读:39今日分享:10

qt如何处理qtcpsocket粘包

今天小编给大家带来的是qt如何处理qtcpsocket粘包,希望能帮助到大家!
工具/原料

PC

方法/步骤
2

2.发送端将数据打包,接收端将数据接收到缓冲区后,从缓冲区起始处解析数据,先找到包头,然后找到包头中表示包体大小的字段,根据包体大小找到包体数据。

3

3.粘包处理前服务器端发送数据://出现一个新连接时调用void myTcpServer::incomingConnection(int socketDescriptor) {    clientConnection = new QTcpSocket;    clientConnection->setSocketDescriptor(socketDescriptor);    clientConnection->write('data1');    clientConnection->write('data2');    clientConnection->write('data3'); }

4

4.客户端接收数据void myTcpClient::slotRead() {    while(tcpSocket->bytesAvailable()>0)    {        int length = tcpSocket->bytesAvailable();        char buf[length];        tcpSocket->read(buf, length);        printf('%s\n', buf);    } }

5

5.粘包处理后服务器端#pragma pack(push, 1) //按照1字节对齐typedef struct{    int len;          //包头,包体长度    char data[1024];  //包体}NetPacket;#pragma pack(pop)//出现一个新连接时调用void myTcpServer::incomingConnection(int socketDescriptor) {    clientConnection = new QTcpSocket;    clientConnection->setSocketDescriptor(socketDescriptor);    char *d1 = 'data1';    char *d2 = 'data2';    char *d3 = 'data3';    NetPacket p1, p2, p3;    p1.len = sizeof('data1');     //封装第一个数据包    memcpy(p1.data, d1, p1.len);    p2.len = sizeof('data2');    memcpy(p2.data, d2, p2.len);    p3.len = sizeof('data3');    memcpy(p3.data, d3, p3.len);    clientConnection->write((char *)&p1, sizeof(int) + p1.len);  //发送数据包    clientConnection->write((char *)&p2, sizeof(int) + p2.len); clientConnection->write((char *)&p3, sizeof(int) + p3.len); }

6

6.客户端void myTcpClient::slotRead() {    while(tcpSocket->bytesAvailable()>0)    {        int len;        char buf[1024];    //接收数据的缓冲区        char tmpBuf[1024]; //存放包体        int nOffset = 0;   //偏移        int n = tcpSocket->bytesAvailable(); //接收到的字节数        tcpSocket->read(buf, n);                    memcpy(&len, buf, sizeof(int));    //包头:包体长度        nOffset += sizeof(int);          memcpy(tmpBuf, buf+nOffset, len);  //包体        nOffset += len;        printf('%s\n', tmpBuf);            //打印包体        memcpy(&len, buf, sizeof(int));        nOffset += sizeof(int);        memcpy(tmpBuf, buf+nOffset, len);        nOffset += len;        printf('%s\n', tmpBuf);        memcpy(&len, buf, sizeof(int));        nOffset += sizeof(int);        memcpy(tmpBuf, buf+nOffset, len);        nOffset += len;        printf('%s\n', tmpBuf);    } }

注意事项
1

网络虽好,但要注意劳逸结合哦!

2

如果是青少年,小编在这里提示大家千万不能沉迷网络!

推荐信息