广播组

客户端1
widget.h
#ifndef WIDGET_H#define WIDGET_H#include <QWidget>#include <QUdpSocket> //UDP套接字namespace Ui {class Widget;}class Widget : public QWidget{ Q_OBJECTpublic: explicit Widget(QWidget *parent = 0); ~Widget(); void dealMsg(); // 槽函数,处理对方发送过来的数据private slots: void on_buttonSend_clicked();private: Ui::Widget *ui; QUdpSocket *udpSoket; //UDP套接字};#endif // WIDGET_H
widget.cpp
#include "widget.h"#include "ui_widget.h"#include <QHostAddress>Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget){ ui->setupUi(this); // 分配空间,指定父对象 udpSoket = new QUdpSocket(this); // 绑定// udpSoket->bind(8888); udpSoket->bind(QHostAddress::AnyIPv4, 8888); // 如果用了组播就要用IPV4 // 加入某个组播 组播的地址是D类地址 udpSoket->joinMulticastGroup(QHostAddress("224.0.0.2")); this->setWindowTitle("服务器端口为:8888"); // 当对方成功发送过来,自动触发readyRead() connect(udpSoket, &QUdpSocket::readyRead, this, &Widget::dealMsg);}Widget::~Widget(){ delete ui;}void Widget::dealMsg(){ // 读取对方发送过来的内容 char buf[1024] = {0}; // 对方地址 QHostAddress cliAddr; // 对方端口 quint16 port; qint64 len = udpSoket->readDatagram(buf, sizeof(buf), &cliAddr, &port); if(len > 0) { // 格式化 [192.68.2.2:8888]aaa QString str = QString("[%1:%2] %3") .arg(cliAddr.toString()) .arg(port) .arg(buf); // 给编辑区设置内容 ui->textEdit->setText(str); }}// 发送按钮void Widget::on_buttonSend_clicked(){ // 先获取对方的IP和端口 QString ip = ui->lineEditIP->text(); qint16 port = ui->lineEditPort->text().toInt(); // 获取编辑器内容 QString str = ui->textEdit->toPlainText(); // 给指定的IP发送数据 udpSoket->writeDatagram(str.toUtf8(), QHostAddress(ip), port);}
客户端2
client.h
#ifndef CLIENT_H#define CLIENT_H#include <QWidget>#include <QUdpSocket>namespace Ui {class client;}class client : public QWidget{ Q_OBJECTpublic: explicit client(QWidget *parent = 0); ~client(); void Mess();private slots: void on_buttonSend_clicked();private: Ui::client *ui; QUdpSocket * udpSocket;};#endif // CLIENT_H
client.cpp
#include "client.h"#include "ui_client.h"#include <QHostAddress>client::client(QWidget *parent) : QWidget(parent), ui(new Ui::client){ ui->setupUi(this); this->setWindowTitle("端口号9991"); udpSocket = new QUdpSocket(this); udpSocket->bind(9991); connect(udpSocket, &QUdpSocket::readyRead, this, &client::Mess);}client::~client(){ delete ui;}void client::Mess(){ char buf[1024] = {0}; QHostAddress addre; quint16 port; qint64 leng = udpSocket->readDatagram(buf, sizeof(buf), &addre, &port); if(leng>0) { QString str = QString("[%1:%2] %3") .arg(addre.toString()) .arg(port) .arg(buf); ui->textEdit->setText(str); }}void client::on_buttonSend_clicked(){ QString ip = ui->lineEditIP->text(); qint16 port = ui->lineEditPort->text().toInt(); QString text = ui->textEdit->toPlainText(); // 给指定的IP发送数据 udpSocket->writeDatagram(text.toUtf8(), QHostAddress(ip), port);}
