原来使用的是moveToThread来实现socket,但是有部分需求会用的QThread run,所以贴部分代码来做备忘。
void UdpRecvThread::readPendingDatagrams()
{
while (this->udpSocket->hasPendingDatagrams())
{
QMutexLocker lock(&m_lock);
QNetworkDatagram datagram = udpSocket->receiveDatagram();
QByteArray ba = datagram.data();
if(ba.size() == 0)
continue;
.....
}
}
void UdpRecvThread::run()
{
udpSocket = new QUdpSocket();
if(!udpSocket->bind(m_srcPort,QUdpSocket::ShareAddress |QUdpSocket::ReuseAddressHint))
{
qDebug() << "udp recv socket bind error";
}
udpSocket->setSocketOption(QAbstractSocket::ReceiveBufferSizeSocketOption,128*1024*1024);
connect(udpSocket, &QUdpSocket::readyRead,this,&UdpRecvThread::readPendingDatagrams,Qt::DirectConnection);
exec();
}
void UdpSendThread::run()
{
udpSocket = new QUdpSocket();
// if(!udpSocket->bind(m_srcPort,QUdpSocket::ShareAddress |QUdpSocket::ReuseAddressHint))
// {
// qDebug() << "udp recv socket bind error";
// }
udpSocket->setSocketOption(QAbstractSocket::SendBufferSizeSocketOption,128*1024*1024);
while (!m_bStop)
{
if(m_bPause)
continue;
do
{
res = udpSocket->writeDatagram(data,len,QHostAddress(m_dstIP),m_dstPort);
if(res == -1)
{
QThread::usleep(10);
}
}while(res == -1 && resendCnt <= 3);
}
delete udpSocket;
udpSocket = nullptr;
}