QTcpSocket - How to send two numbers

时间:2017-12-18 08:09:39

标签: c++ qt qtcpsocket

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

this.Focus();

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

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

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

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));
  • 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?

2 个答案:

答案 0 :(得分:1)

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 { drilldown: function(e) { this.update({ xAxis: { plotBands: [{ color: '#FFF', from: -0.5, to: e.seriesOptions.data.length, label: { text: e.point.name, align: 'center' } }], } }, true); if( e.point.name == 'Started - F15' ){ minMaxData_15Fa.toggle(); } }, drillup: function() { this.update({ xAxis: { plotBands: [{ from: 0, to: 0, }], } }, true); if(tableToggle == 'F15'){ minMaxData_15Fa.toggle(); } } to send and receive data:

Client code:

QDataStream

Server code:

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

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

答案 1 :(得分:0)

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

IMAGE_DOS_HEADER
IMAGE_NT_HEADER

it returns new object, and in this line

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

const char * messageIdBytes = buffer.mid(0, 2); function returns temporary object QByteArray, it is converted to const char* using method

mid

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

One thing, in this line

QByteArray::operator const char *() const