我有一个关于 QUdpSocket 的问题:我大约每 0.2 秒在端口上接收50011
到多播地址的 UDP 消息239.0.0.1
(由 wireshark 证明)。
以下代码运行良好(并在每条消息上打印“VALID”)约 1 分钟。之后messageHandler
不再被QUdpSocket's
信号调用readyRead
(即使我已经用wireshark仔细检查过,消息仍在发送中)。
ServiceDiscovery::ServiceDiscovery(QObject *parent) :
QObject(parent),
socket(new QUdpSocket(this))
{
socket->bind(QHostAddress::AnyIPv4, 50011, QUdpSocket::ShareAddress);
socket->joinMulticastGroup(QHostAddress("239.0.0.1"));
connect(socket, &QUdpSocket::readyRead,
this, &ServiceDiscovery::messageHandler,
Qt::DirectConnection);
}
void ServiceDiscovery::messageHandler()
{
if(socket->isOpen()) qDebug("OPEN"); // Does not print, ofc.
if(socket->isReadable()) qDebug("READABLE"); // Does not print.
if(socket->isValid()) qDebug("VALID"); // Suddenly stops.
QByteArray datagram;
while(socket->hasPendingDatagrams()) {
datagram.resize(socket->pendingDatagramSize());
socket->readDatagram(datagram.data(), datagram.size());
Message response(datagram);
if(response.deserialize()) {
if(response.getServiceID() == constants::servicediscovery::SERVICE_ID) {
QByteArray payload = response.getPayload();
if(payload.size() >= 48) {
QString address = QHostAddress(payload.mid(32, 4).toHex().toUInt(nullptr, 16)).toString();
quint16 port = payload.mid(38, 2).toHex().toUInt(nullptr, 16);
emit found(address, port);
}
}
}
}
}
我在这里做错了什么?提前致谢。
编辑:由于评论,我也粘贴了数据报处理。