使用 QTcpSocket 发送字节

Sending Bytes using QTcpSocket

本文关键字:字节 QTcpSocket 使用      更新时间:2023-10-16

我有一个嵌入式设备,我试图通过无线连接通过TCP与之通信。 以下是设备期望的数据结构:

char[] = { 0x55, 0x55, 0x55, 0x55 //header block
    //start data here
    0x01, 0x00, 0x00, 0x00 //example data
    //end data block
    0xAA, 0xAA, 0xAA, 0xAA //footer
    };

我正在尝试使用 QTcpSocket 来写入此数据。 QTcpSocket 将允许我写入字符数据或 QByteArray,但是当我尝试以这两种格式中的任何一种保存此数据时,它会失败。 我成功保存数据的唯一方法是在无符号字符数组中。

我的意思的例子:

char message[12] = {
    0x55, 0x55, 0x55, 0x55,
    0x01, 0x00, 0x00, 0x00,
    0xAA, 0xAA, 0xAA, 0xAA};

但是,此消息块给了我一个错误

C4309: 'initializing' : truncation of constant value.

打印此数据时,结果为:

U U U U
r

R 更像是正方形的边缘,而不是实际的字母

通过将数组从 char 更改为无符号 char 来修复此特定问题

unsigned char message[12] = {
    0x55, 0x55, 0x55, 0x55,
    0x01, 0x00, 0x00, 0x00,
    0xAA, 0xAA, 0xAA, 0xAA};

打印后会输出数据:

85 85 85 85
1 0 0 0
170 170 170 170

这与我正在与之交谈的设备所期望的格式相匹配。 但是,如果我以这种格式输入数据,QTcpSocket 不喜欢这样,并回复:

C2664: 'qint64 QIODevice::write(const QByteArray &)': cannot convert argument 1
from 'unsigned char[20]' to 'const char *'

有没有办法使用 QTcpSocket 发送我想要的数据,或者我需要弄清楚如何使用 Windows 套接字编写此消息?

您可以简单地投射到char *

qint64 ret = socket.write((char *)message, 12);