Qt qudp套接字读取问题

Qt qudp套接字读取问题,qt,qudpsocket,Qt,Qudpsocket,从UDP客户端接收数据时出现问题。我使用的代码是: 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())); qDebu

从UDP客户端接收数据时出现问题。我使用的代码是:

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;
}
但在我的应用程序的控制台输出中,我接收到以下集群数据:

Message from:  "192.168.1.110" 
Message port:  5001 
Message:  "X¿
Size:  20 
Pending datagrams:  false 
"58bf80" 
您可以看到,只接收到数据“58bf80”的第一部分。数据报似乎没有任何限制,套接字运行良好。我不知道会发生什么


提前感谢。

截断可能发生在从
QByteArray
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
QByteArray data; //The data you got!
QString str = QString(data.toHex()); //Perform the conversion to hex encoded and to string