先贴代码:
while (1){if(isStop)return;if (!udpSocket){ //当指针为空时新建对象udpSocket = new QUdpSocket();udpSocket->bind(QHostAddress::AnyIPv4,5453);SendMsg(QByteArray("123"));}//connect 只监听一次connect(udpSocket,SIGNAL(readyRead()),this,SLOT(new_Servermsg_slot()))}
在connect中监听readyread 但是却怎么也监听不到发来的数据,这令我非常的纳闷,经过查资料发现 是因为在循环中,循环过快,导致connect来不及处理数据,所以使用: waitForReadyRead()
将循环进行阻塞 当有数据读入时取消阻塞 进入下一轮循环
加上下面这一行程序正常:
udpSocket->waitForReadyRead();
while (1){if(isStop)return;if (!udpSocket){ //当指针为空时新建对象udpSocket = new QUdpSocket();udpSocket->bind(QHostAddress::AnyIPv4,5453);SendMsg(QByteArray("123"));}//connect 只监听一次connect(udpSocket,SIGNAL(readyRead()),this,SLOT(new_Servermsg_slot()));//waitForReadyRead 阻塞作用 当有数据读取到时才取消阻塞 这里才进入下一轮循环udpSocket->waitForReadyRead();//qDebug()<<"MyThread::startThreadSlot QThread::currentThreadId()=="<<QThread::currentThreadId();}