Qt实现UDP广播简例

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/HackerTom/article/details/73604924

参考

第36篇 网络(六)UDP

Notes

  • 局域网聊天的用户上线、群发要用到 UDP 的广播
  • 加上了简单的图形界面
  • 从单播到广播,差别就只是writeDatagram()QHostAddress 那个参数,QHostAddress::Broadcast 就是广播,QHostAddress(“*.*.*.*”) 就是单播
  • cmd里用ipconfig看 IP,发现有很多个 IP…广播实验时自己电脑收得到,舍友电脑却收不到(连着同一个wifi),可能是网络问题?

Code

发送端

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QUdpSocket>

namespace Ui {
    class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void on_pushButton_clicked();

private:
    Ui::MainWindow *ui;
    QUdpSocket *us;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QByteArray>
#include <QHostAddress>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    us = new QUdpSocket;
}

MainWindow::~MainWindow()
{
    delete ui;
    delete us;
}

void MainWindow::on_pushButton_clicked()
{
    QByteArray ba = "iTom is comming...";
    /* 单播和广播的区别在第二个参数 */
    us->writeDatagram(ba, QHostAddress::Broadcast, 3333);
}

main.cpp

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

接收端

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QUdpSocket>

namespace Ui {
    class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void read_msg();

private:
    Ui::MainWindow *ui;
    QUdpSocket *us;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QByteArray>
#include <QHostAddress>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    us = new QUdpSocket;
    us->bind(3333, QUdpSocket::ShareAddress);
    connect(us, SIGNAL(readyRead()), this, SLOT(read_msg()));
}

MainWindow::~MainWindow()
{
    delete ui;
    delete us;
}

void MainWindow::read_msg()
{
    QByteArray ba;
    while(us->hasPendingDatagrams())
    {
        ba.resize(us->pendingDatagramSize());
        us->readDatagram(ba.data(), ba.size());
        ui->plainTextEdit->appendPlainText(QString(ba));
    }
}

main.cpp

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

截图

广播前

before_broadcast

广播后

after_broadcast

展开阅读全文

没有更多推荐了,返回首页