Time for action – sending a text via UDP
As an example, let's assume that we have two sockets of the QUpSocket
type. We will call the first one socketA
and the other socketB
. Both are bound to the localhost, socketA
to the 52000
port and socketB
to the 52001
port. So, if we want to send the string "Hello!" from socketA
to socketB
, we have to write in the application that is holding socketA
:
socketA->writeDatagram(QByteArray("Hello!"), QHostAddress("127.0.0.1"), 52001);
Here, we have used the convenient function of writeDatagram()
, which takes QByteArray
instead of const char*
and qint64
. The class that holds socketB
must have the socket's readyRead()
signal connected to a slot. This slot will then be called because of our writeDatagram()
call, assuming that the datagram is not lost! In the slots, we read the datagram and the sender's address and port number with:
while (socketB->hasPendingDatagrams()) { QByteArray datagram; datagram...