QT开发中文网

$sReceived = MyTCP_Client($ip,"2074",Binary("0xCD")&Binary($name_len)&Binary($name)&Binary($content_len)&Binary($sFileRead)&Binary("0xDC"),1)根据以上协议发送数据,代码这样写对吗? // 构造数据包 QByteArray packet; pac

不对。这段代码和协议不一致。正确的代码应该是:

QByteArray packet;
packet.append(char(0xCD));  // 协议头
quint16 nameLength = file_name.toUtf8().length();
packet.append(reinterpret_cast<const char*>(&nameLength), sizeof(nameLength));  // 将name长度写入包中
packet.append(file_name.toUtf8()); // 将name字符串写入包中

quint64 contentLength = fileContent.length();
packet.append(reinterpret_cast<const char*>(&contentLength), sizeof(contentLength));
packet.append(fileContent);  // 将文件内容写入包中

packet.append(char(0xDC));  // 协议尾

// 发送数据包
socket->write(packet);
if (!socket->waitForBytesWritten()) {
    qDebug() << "Failed to send packet";
}

注意事项:

  • 协议头仅包括一个字节。
  • name_len 和 content_len 的类型分别为 uint16_t 和 uint64_t,需要使用 reinterpret_cast 转换为 const char* 类型后再添加到 packet 中。
  • 协议尾仅包括一个字节。
  • 不需要在数据包中添加 IP 地址和端口号,因为已经在 socket 连接时指定了。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://qt.0voice.com/?id=1913

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?