QT += network
udp.h
#ifndef UDP_H
#define UDP_H
#include <QObject>
#include <QUdpSocket>
class Udp : public QObject
{
Q_OBJECT
public:
explicit Udp(QObject *parent = 0);
void startRun();
private:
QUdpSocket * pUdpSocket = nullptr ;
void processTheDatagram(QByteArray);
signals:
private slots:
void readPendingDatagrams();
};
#endif // UDP_H
udp.cpp
#include "udp.h"
Udp::Udp(QObject *parent) : QObject(parent)
{
}
void Udp::startRun()
{
pUdpSocket = new QUdpSocket(this);
// 以共享地址和端口的方式绑定,允许其他的也绑定该端口,默认 QAbstractSocket::DefaultForPlatform
pUdpSocket->bind(QHostAddress("10.128.99.138"),8080,
QAbstractSocket::ShareAddress);
connect(pUdpSocket, SIGNAL(readyRead()),
this, SLOT(readPendingDatagrams()));
}
void Udp::processTheDatagram(QByteArray data)
{
// do something
qDebug() << QString(data);
}
// 处理接收的数据
void Udp::readPendingDatagrams()
{
while (pUdpSocket->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(pUdpSocket->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
pUdpSocket->readDatagram(datagram.data(), datagram.size(),
&sender, &senderPort);
processTheDatagram(datagram);
}
}