1、在*.pro文件中添加:
QT += network
QT += network
2、在代码中添加:
#include <QtNetwork>
QUdpSocket *m_pUdpSocket; //udp socket
m_pUdpSocket = new QUdpSocket(this);
m_pUdpSocket->bind(QHostAddress::Any, port);
connect(m_pUdpSocket, SIGNAL(readyRead()), this, SLOT(slotReadUdpData()));
//接收数据
void Mainwindow::slotReadUdpData()
{
QByteArray byteArray;
while (m_pUdpSocket->hasPendingDatagrams())
{
byteArray.resize(m_pUdpSocket->pendingDatagramSize());
m_pUdpSocket->readDatagram(byteArray.data(), byteArray.size());
//处理接收到的数据
processPakcet(byteArray);
}
}