PDA

View Full Version : Reading UDP data properly



ankit.1g@gmail.com
15th February 2016, 18:52
Hi all,

I am trying to read back the udp data , sent from my stepper motor. Reply varies from 3-12 bytes.

I am currently doing this to read my udp data:


qint64 size = udpSocket->pendingDatagramSize();
QHostAddress sender;
quint16 senderPort;
char* reply = new char[size]
qint64 res = udpSocket->readDatagram( reply, size, &sender, &senderPort );

char buf[12];
for ( int i = 2; i <= 11; ++i )
buf[ i -2 ] = reply[ i ];

ui->Position->setText(buf);

The problem I am facing is that sometime there are only 4 bytes sometime there are 11 bytes and when there are less bytes suppose 4-5 my text box will be filled with weird characters of unreadable format.
how can I change my current code to just read proper bytes received.

ChrisW67
15th February 2016, 19:30
If you persist using basic char[] then you are responsible for ensuring that the buffer is Nul terminated '\0' before trying to use the buffer as a C string. There is also no guarantee that the bytes of the datagram are printable characters in the first place.

Currently your datagram buffer is a memory leak. If you use QByteArray exactly as in the QUdpSocket docs then you will have neither the memory leak nor nul termination issues.

ankit.1g@gmail.com
15th February 2016, 20:05
If you persist using basic char[] then you are responsible for ensuring that the buffer is Nul terminated '\0' before trying to use the buffer as a C string. There is also no guarantee that the bytes of the datagram are printable characters in the first place.

Currently your datagram buffer is a memory leak. If you use QByteArray exactly as in the QUdpSocket docs then you will have neither the memory leak nor nul termination issues.

thank you very much, but how can I change my code to use QByteArray? should i change char* reply to QByteArray reply?

Added after 5 minutes:

I get Error " conversion to QByteArray to char* is ambiguous :

qint64 size = udpSocket->pendingDatagramSize();
QByteArray datagram;
datagram.resize(size);
udpSocket->readDatagram( datagram, size, &sender, &senderPort );

ChrisW67
16th February 2016, 12:34
At the risk of sounding like a broken record...

If you use QByteArray exactly as in the QUdpSocket docs then you will have neither the memory leak nor nul termnation issues.