因此,UDP 服务器显然只是侦听某个端口并处理带有源 IP 和 PORT 的字节数组:
// 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);
}
}
非常好。这实际上有效,正如我使用这个 python 片段验证的那样:
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))
字节数组甚至包含“PING”。所以我正要写一个客户端。我假设客户端将简单地使用QUdpSocket::sendDatagram
. 但是他怎么能收到数据呢?
首先我想我会打电话bind(SERVER_ADDRESS_HERE, 6660)
。但显然他们不能都在同一个端口上监听。
那么如何为上面的服务器编写一个客户端呢?