【发布时间】:2016-12-07 18:50:58
【问题描述】:
大家!
我在使用 QUdpSocket 和 readyRead 信号时遇到了一个奇怪的问题,我可以说它不像我想的那样工作,
我创建了一个 QUdpSocket 并将其绑定到某个端口,将 readyRead 信号连接到我的插槽并读取所有待处理的数据报,如下所示
if(!udp_listener)
{
udp_listener = new QUdpSocket(this);
connect(udp_listener, SiGNAL(readyRead()), this, SLOT(readBuffers(), Qt::QueuedConnection);
// the rate of receiving data is 10 msec if i dont put Qt::QueuedConnection, it didn't receive any more signal after first received. why ???
// change the rate of data to 1 sec and this code work well without Qt::QueuedConnection !!!
}
udp_lister.bind(Any, 5555);
还有我的 readBuffers 代码
void readBuffers() {
QString buffer;
while(udp_listener->hasPendingDatagrams()) {
QByteArray received;
received.resize(udp_listener->pendingDatagramSize());
udp_listener->readDatagram(received, received.size(), 0,0);
buffer.append(received);
// Do some job in 1 msec on buffer and take data from buffer
if(/* some works done */) buffer.clear(); // almost every time my buffer got cleared
}
}
我认为使用 Qt::QueuedConnection 解决了我的问题,但今天我在我的项目中添加了另一个小部件并每 100 毫秒更新一次。我不知道怎么回事,但我的插槽在 2 秒后不再发出信号。
如果我将定时器间隔或发送数据速率更改为 1 秒,一切都很好。
我所有的类和小部件都位于主程序的线程中,我不使用其他线程,但似乎我应该这样做!
那么为什么 Qt 事件循环会丢弃信号?
我检查了我的套接字状态,它在 Bound 之后没有改变。
提前致谢
【问题讨论】:
-
也许你的程序卡在
while(udp_listener->hasPendingDatagrams())循环中? -
不,我的 Gui 对所有类型的信号都有响应
-
我发现 this 和 this bug report 似乎相关。
-
@thuga 实际上我在 Windows 7 平台上的 Qt 5.6 中编写了这段代码,但我认为它与这个错误有关。您认为更好的实施方式是什么?在答案中给出一些建议,以便我将您的答案标记为正确答案。感谢搜索
-
我在带有 Qt 5.5.1 的 Windows 7 上对此进行了测试,无论我让它发送数据报的速度有多快,它都能正常工作。不过,我在同一台机器上运行了发送者和侦听器,不确定是否重要。
标签: c++ qt qeventloop qudpsocket