UDP Unicast



  • Can the QUdpSocket class be set up to natively support UDP Unicast communications? I can't seem to find anything in the documentation...or maybe I just don't know what I'm looking for. An example would be great.

    Thanks!



  • Unicast is the default model. You don't need to setup anything.



  • Thanks. Was just confused since the docs say nothing about "unicast".

    So to set up for unicast UDP, for which I can both send and receive over the same socket, does this look right?

    @void MyUnicastUdpServer::initSocket()
    {
    // initialize UDP for unicast to: 12.34.56.78, port 5678 (bogus IP and port)

     udpSocket = new QUdpSocket(this);
     udpSocket->bind(QHostAddress(12.34.56.78, 5678);
    
     connect(udpSocket, SIGNAL(readyRead()),
             this, SLOT(readPendingDatagrams()));
    

    }

    void MyUnicastUdpServer::readPendingDatagrams()
    {
    while (udpSocket->hasPendingDatagrams()) {
    QByteArray datagram;
    datagram.resize(udpSocket->pendingDatagramSize());
    QHostAddress sender;
    quint16 senderPort;

         udpSocket->readDatagram(datagram.data(), datagram.size(),
                                 &sender, &senderPort);
    
         // process The Datagram
    

    }

    void MyUnicastUdpServer::sendDatagram(QByteArray dgram)
    {
    udpSocket->writeDatagram(dgram.data(),dgram.size(), QHostAddress(12.34.56.78, 5678 );
    }
    @

    Thanks.



  • I never worked with UDP sockets, but it looks quite ok for me with an exception to the sendDatagram() method. The host address and port used there is that of the host you are sending to (the "remote" host); you give the local address and probably send to yourself :-)


Log in to reply
 

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