I have an issue when I receive data from a UDP client. The code that I used is:
MyUDP::MyUDP(QObject *parent) :
QObject(parent)
{
socket = new QUdpSocket(this);
socket->bind(QHostAddress("192.168.1.10"),2000);
connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()));
qDebug() << "Socket establert";
}
void MyUDP::HelloUDP()
{
QByteArray Data;
Data.append("R");
socket->writeDatagram(Data, QHostAddress("192.168.1.110"), 5001);
qDebug() << "Enviat datagrama";
}
void MyUDP::readyRead()
{
QByteArray buffer;
buffer.resize(socket->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
socket->readDatagram(buffer.data(), buffer.size(), &sender, &senderPort);
qDebug() << "Message from: " << sender.toString();
qDebug() << "Message port: " << senderPort;
qDebug() << "Message: " << buffer;
qDebug() << "Size: " << buffer.size();
qDebug() << "Pending datagrams: " << socket->hasPendingDatagrams();
QString str(buffer);
QString res = str.toAscii().toHex(); qDebug() << res;
}
The problem is that in Wireshark I receive this data (all the data):
Internet Protocol Version 4, Src: 192.168.1.110, Dst: 192.168.1.10
User Datagram Protocol, Src Port: 5001, Dst Port: 2000
Data (20 bytes)
Data: 58bf80000059bf800000410000000053bf800000
[Length: 20]
But at the console output of my application I receive this trunkated data:
Message from: "192.168.1.110"
Message port: 5001
Message: "X¿
Size: 20
Pending datagrams: false
"58bf80"
You can see that only the first part of data "58bf80" is received. It seems that the datagram no has any limitation, and the socket runs fine. I don't see what may be happening.
Thanks in advance.
The truncation probably happens in conversion from QByteArray
to QString
, the string getting truncated in null terminator (byte with value 0).
To correctly convert from QByteArray
to hex encoded QString
use toHex
function, like on the following example:
QByteArray data; //The data you got!
QString str = QString(data.toHex()); //Perform the conversion to hex encoded and to string