大家!
我在使用 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 之后没有改变。
提前致谢