头文件定义
工程配置中加入:QT += network
#include <QObject>
#include <QUdpSocket>
class QtUdp : public QObject
{
Q_OBJECT
public:
UdpReceiver(QObject *p = 0);
~UdpReceiver();
public slots:
void receive();
private:
QUdpSocket *uSocket;
}
CPP实现
#include <QByteArray>
#include <iostream>
#include "QtUdp .h"
const quint16 UDP_PORT = 2333;
QtUdp ::QtUdp (QObject *p) :
QObject(p)
{
uSocket = new QUdpSocket;
uSocket->bind(QHostAddress("127.0.0.1"), UDP_PORT);
connect(uSocket, SIGNAL(readyRead()), this, SLOT(receive()));
}
QtUdp ::~QtUdp ()
{
delete uSocket;
}
void QtUdp ::receive()
{
QByteArray ba;
while(uSocket->hasPendingDatagrams())
{
ba.resize(uSocket->pendingDatagramSize());
uSocket->readDatagram(ba.data(), ba.size());
std::cout << ba.data() << std::endl;
}
}