PDA

View Full Version : Sending binary data packet over TCPSocket



Miss Engineer
3rd April 2014, 01:17
Hello,
I am a newbie to C++ and Qt and I'm working on a project using Qt now. I want to send a packet over the TCPSocket, the packet structure is as follows:

SYNC_WORD+RESERVE+PAYLOAD_LENGTH+PAYLOAD+ENDBYTE1+ ENDBYTE2
and size:
(1B)+(1B)+(2B)+(VAR B)+(1B)+(1B)

The payload is the contents of a QlineEdit

How do I do that? I have tried lots of alternatives, the last of which I defined the packet as an array of characters, but the RESERVE byte is currently 0x00 and it translates into NULL.
Any help would be appreciated.

ChrisW67
3rd April 2014, 01:51
QByteArray can hold arbitrary binary data and is easily written to the socket device. In a rough, raw form:


const QByteArray payload = ui->lineEdit->text().toUtf8();
QByteArray message;
message.append('\x00'); // sync
message.append('\x00'); // reserved
message.append(static_cast<char>(payload.size() & 0xFF)); // payload size LSB
message.append(static_cast<char>(payload.size() >> 8 & 0xFF)); // payload size MSB
message.append(payload);
message.append('\x00'); // end byte 1
message.append('\x00'); // end byte 2
qDebug() << message.toHex();

Miss Engineer
17th April 2014, 07:43
This worked perfectly. Thank you very much.


QByteArray can hold arbitrary binary data and is easily written to the socket device. In a rough, raw form:


const QByteArray payload = ui->lineEdit->text().toUtf8();
QByteArray message;
message.append('\x00'); // sync
message.append('\x00'); // reserved
message.append(static_cast<char>(payload.size() & 0xFF)); // payload size LSB
message.append(static_cast<char>(payload.size() >> 8 & 0xFF)); // payload size MSB
message.append(payload);
message.append('\x00'); // end byte 1
message.append('\x00'); // end byte 2
qDebug() << message.toHex();