码迷,mamicode.com
首页 > 其他好文 > 详细

qt udp

时间:2016-04-28 16:58:10      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

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

 

qt udp

标签:

原文地址:http://www.cnblogs.com/qk2015/p/5443162.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!