So, UDP server apparently just listens on some port and handles byte arrays which come with IP and PORT of the source:
// In this code, listener is QUdpSocket*
FileServer::FileServer(QObject *parent)
: QObject(parent)
, listener(new QUdpSocket(this))
{
// bind to listening port
listener->bind(QHostAddress::Any, 6660);
connect(listener, &QUdpSocket::readyRead,
this, &FileServer::readPendingDatagrams, Qt::QueuedConnection);
}
void FileServer::readPendingDatagrams()
{
while (listener->hasPendingDatagrams()) {
// This is how this is done in new QT
//QNetworkDatagram datagram = listener->receiveDatagram();
//processTheDatagram(datagram);
// This is how it is done in old QT
QByteArray datagram;
datagram.resize(listener->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
listener->readDatagram(datagram.data(), datagram.size(),
&sender, &senderPort);
processDatagram(datagram, sender, senderPort);
}
}
Very nice. This actually works, as I verified using this python snippet:
import socket
host="127.0.0.1"
port=6660
udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_sock.sendto(b'PING', (host, port))
The byte array even contained "PING". So I was about to write a client. I assume client will simply send data using QUdpSocket::sendDatagram
. But how can he receive data?
First I thought I will call bind(SERVER_ADDRESS_HERE, 6660)
. But clearly they can't both listen on the same port.
So how do I write a client for the server above?