标签:
#ifndef MUDP_H #define MUDP_H #include <QObject> #include <QUdpSocket> class mudp : public QObject { Q_OBJECT public: explicit mudp(QObject *parent = 0); QUdpSocket *udpSocket ; void initSocket(); public slots: void readPendingDatagrams(); }; #endif // MUDP_H
#include "mudp.h" #define UDP_PORT 8080 mudp::mudp(QObject *parent) : QObject(parent) { initSocket(); } void mudp::initSocket() { udpSocket = new QUdpSocket(); udpSocket->bind(QHostAddress::AnyIPv4, UDP_PORT, QUdpSocket::ReuseAddressHint); connect(udpSocket, SIGNAL(readyRead()),this, SLOT(readPendingDatagrams())); } void mudp::readPendingDatagrams() { while (udpSocket->hasPendingDatagrams()) { QByteArray datagram; datagram.resize(udpSocket->pendingDatagramSize()); QHostAddress sender; quint16 senderPort; udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort); qDebug()<<sender.toString()<<senderPort<<(datagram); udpSocket->writeDatagram(datagram.data(), datagram.size(),sender, senderPort); } }
#include "mainwindow.h" #include "mudp.h" mudp *udp; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { udp = new mudp; } MainWindow::~MainWindow() { }
标签:
原文地址:http://www.cnblogs.com/qk2015/p/5443162.html