qt udp

#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()
{
}

 

转载于:https://www.cnblogs.com/qk2015/p/5443162.html

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页