简体   繁体   中英

QTcpSocket - How to send two numbers

Client Application sends two (ushort) numbers via QTcpSocket to the server:

ushort MessageId = 4;
ushort MessageSize = 0;
socket->write((const char*) &MessageId, sizeof(ushort));
socket->write((const char*) &MessageSize, sizeof(ushort));
socket->waitForBytesWritten();

Server Application receives the 4 bytes long message and puts it into a QByteArray buffer then decodes the numbers:

int bytes = socket->bytesAvailable();
QByteArray buffer = socket->read(bytes)

const char * messageIdBytes = buffer.mid(0, 2);
ushort messageId = (ushort)(*messageIdBytes);

const char * messageSizeBytes = buffer.mid(2, 4);
ushort messageSize = (ushort)(*messageSizeBytes );

qDebug() << QString("MessageId Bits: [%1], Value: [%2].").arg(QString::number(messageId, 2), QString::number(messageId));
qDebug() << QString("MessageSize Bits: [%1], Value: [%2].").arg(QString::number(messageSize, 2), QString::number(messageSize));

This gives the following server output: (I added the spaces for readability)

MessageId Bits: [1111 1111 1101 1101], Value: [65501].
MessageSize Bits: [1111 1111 1101 1101], Value: [65501].
  • Problem: the server output should receive MessageId 4 and MessageSize 0.
  • Observation: sending different values from the client doessn't even affect the server output. It's always that weird number 65501..
  • Interesting: it does work however if I only write one number instead of two!

Any idea what I'm doing wrong?

Sending raw numbers is never a good idea. Reasons for why this could be going wrong are:

  • Desychronisation
  • Endianess
  • Parsing errors
  • ...

Best practice in Qt is to use QDataStream to send and receive data:

Client code:

QDataStream stream(socket);
stream << MessageId << MessageSize;

Server code:

QDataStream stream(socket);
ushort MessageId, MessageSize;
stream.startTransaction();
stream >> MessageId >> MessageSize;
if(stream.commitTransaction())
    qDebug() << "Worked:" << MessageId << MessageSize;
else
    qDebug() << "Error:" << stream.status();

You can read more about QDataStream and read transactions at the Documentation

I think you are reading junk data, look at mid declaration

QByteArray QByteArray::mid(int pos, int len = -1) const

it returns new object, and in this line

const char * messageIdBytes = buffer.mid(0, 2);

mid function returns temporary object QByteArray , it is converted to const char* using method

QByteArray::operator const char *() const

when temporary object is deleted, your pointer is dangling. Then you are reading junk data.

One thing, in this line

buffer.mid(2, 4); // should be 2 as second argument, this is not index but length

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM