使用QTcpSocket发送字节

时间:2015-01-15 17:53:45

标签: c++ qt sockets bytearray qtcpsocket

我有一个嵌入式设备,我试图通过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将允许我编写char数据或QByteArray,但是当我尝试以这些格式之一保存这些数据时,它会失败。我成功保存数据的唯一方法是使用unsigned char数组。

我的意思是:

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更改为unsigned 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套接字编写此消息?

1 个答案:

答案 0 :(得分:1)

您可以简单地转换为char *

qint64 ret = socket.write((char *)message, 12);
相关问题