Support on writeDatagram QUdpSocket function



  • Hello All,

    I am trying to write UDP message to the socket.

    QUdpSocket Msg_socket;
    Msg_socket->writeDatagram(const char *data, qint64 size, const QHostAddress &address, quint16 port);

    Here writeDatagram function support const char *data, and I have my UDP message in the form of an array of unsigned char * .

    If I change my array from unsigned char * to char * in order to use writeDatagram function I see overflowing of my data to the negative range.

    Would like to know

    1. If there is any other function in QT which would support in writing my data to socket apart from the one mentioned above ?
    2. If you have any suggestion on how to handle this situation .

    Thank you for your time.


  • Qt Champions 2016



  • QUdpSocket is a QIODevice so the usual QDatastream method is the preferred one. see http://doc.qt.io/qt-5/qdatastream.html#details

    @NarutoKun said in Support on writeDatagram QUdpSocket function:

    If I change my array from unsigned char * to char * in order to use writeDatagram function I see overflowing of my data to the negative range.

    I guess you are using a reinterpret_cast<char *> so what's the problem if it goes to negative numbers?! just use reinterpret_cast<unsigned char *> to get back the original.



  • Using this with no problems:

    QByteArray datagram;
    cmd_socket->writeDatagram(datagram.data(), datagram.size(), QHostAddress::LocalHost, CMD_SOCK_PORT);
    


  • Re: Support on writeDatagram QUdpSocket function

    @mrjj , @VRonin & @McLion

    Thank you all for your inputs. All your inputs helped me get through my problem.

    This is what I came up with and now I am able to transmit my data correctly and observing the right behavior.

    QUdpSocket socketwr;
    char pack_data[ ] = {xx, xx xx ......... };
    :
    :
    :
    :
    QByteArray data_to_socket = QByteArray::fromRawData(pack_data, pack_data_len);
    socketwr->writeDatagram(data_to_socket, *receiver_ip_add, receiver_port_add);

    Thanks again!!!
    Good Day.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.