不对。这段代码和协议不一致。正确的代码应该是:
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 连接时指定了。