0

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.

4

1 回答 1

1

截断可能发生在从QByteArrayto的转换中QString,字符串在空终止符(值为 0 的字节)中被截断。

要正确转换QByteArray为十六进制编码的QString使用toHex函数,如下例所示:

QByteArray data; //The data you got!
QString str = QString(data.toHex()); //Perform the conversion to hex encoded and to string
于 2017-02-01T16:00:28.240 回答