这里用的无线网:ipconfig查看下ip

QT之UDP通信_数据

udpsend:


#include "udpSend.h"
//#include <QUdpSocket>
#include <QMessageBox>

udpSend::udpSend(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);

mSocket = new QUdpSocket();


}
void udpSend::on_sendBt_clicked()
{
//单播
qint64 len = mSocket->writeDatagram(ui.textEdit->toPlainText().toUtf8(),QHostAddress("192.168.0.194"),8007);


//组播ip地址范围:224.0.0.0-239.255.255.255
//qint64 len = mSocket->writeDatagram(ui.textEdit->toPlainText().toUtf8(),QHostAddress("224.0.0.100"),6677);

//广播
// qint64 len = mSocket->writeDatagram(ui.textEdit->toPlainText().toUtf8(), QHostAddress::Broadcast, 8007);
//QMessageBox::information(this, "Warning", ui.textEdit->toPlainText().toUtf8());

}

udpSend.cpp:



#pragma once

#include <QtWidgets/QMainWindow>
#include "ui_udpSend.h"
#include <QUdpSocket>


class udpSend : public QMainWindow
{
Q_OBJECT

public:
udpSend(QWidget *parent = Q_NULLPTR);

private:
Ui::udpSendClass ui;
QUdpSocket *mSocket;

private slots:
void on_sendBt_clicked();
};

udpSend.h



#include "udpRecv.h"
#include <QMessageBox>
#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif

udpRecv::udpRecv(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
//创建对象 初始化
mSocket = new QUdpSocket();

//绑定
mSocket->bind(QHostAddress::AnyIPv4,8007);
//QMessageBox::information(this, "Warning", QString(QHostAddress::AnyIPv4));//不会乱码
//关联读数据信号readyread
connect(mSocket,SIGNAL(readyRead()),this,SLOT(read_data()));

}

void udpRecv::read_data()
{
QByteArray array;
QHostAddress address;
quint16 port;
array.resize(mSocket->bytesAvailable());//根据可读数据来设置空间大小
mSocket->readDatagram(array.data(),array.size(),&address,&port); //读取数据
ui.listWidget->addItem(array);//显示数据
//发送反馈数据

}

void udpRecv::on_checkBox_clicked(bool checked)
{
if(checked)
{
//加入组播
mSocket->joinMulticastGroup(QHostAddress("224.0.0.100"));
}

else
{
//退出组播
mSocket->leaveMulticastGroup(QHostAddress("224.0.0.100"));

}

}

QT之UDP通信_#include_02

udpRecv:

udpRecv.cpp



#pragma once

#include <QtWidgets/QMainWindow>
#include "ui_udpRecv.h"
#include <QUdpSocket>

class udpRecv : public QMainWindow
{
Q_OBJECT

public:
udpRecv(QWidget *parent = Q_NULLPTR);

private:
Ui::udpRecvClass ui;
QUdpSocket *mSocket;

private slots:
void on_checkBox_clicked(bool);
void read_data();
};

QT之UDP通信_#include_03

测试结果:

QT之UDP通信_#if_04