feat: Udp通信:multicate(组播)的使用

This commit is contained in:
touwoyimuli 2019-12-05 00:05:00 +08:00
parent 16b00f6d4b
commit 1b18305928
14 changed files with 499 additions and 0 deletions

View File

@ -0,0 +1,171 @@
/*
* Copyright (C) 2019 ~ 2019 touwoyimuli. All rights reserved.
*
* Author: touwoyimuli <touwoyimuli@gmai.com>
*
* github: https://github.com/touwoyimuli
* blogs: https://touwoyimuli.github.io/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://touwoyimuli.github.io/>.
*/
#include "ExMulticast.h"
#include "ui_ExMulticast.h"
ExMulticast::ExMulticast(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::ExMulticast)
{
ui->setupUi(this);
setWindowTitle("Udp通信multicate(组播)的使用");
QString hostName = QHostInfo::localHostName();
QString ip = getLocalIp();
ui->plainTextEdit->appendPlainText("主机名称:" + hostName + "\n主机IP" + ip + "\n");
m_labSocketState = new QLabel("Socket状态");
m_labSocketState->setMinimumWidth(200);
ui->statusBar->addWidget(m_labSocketState);
ui->comboBoxIp->addItem(getLocalIp());
m_udpSocket = new QUdpSocket(this); //用于通讯使用的 Socket
//Multicast路由层次1表示只在同一局域网内
//组播TTL: 生存时间每跨1个路由会减1多播无法跨过大多数路由所以为1
//默认值是1表示数据包只能在本地的子网中传送。
m_udpSocket->setSocketOption(QAbstractSocket::MulticastTtlOption, 1);
connect(m_udpSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(onSocketStateChange(QAbstractSocket::SocketState)));
onSocketStateChange(m_udpSocket->state());
connect(m_udpSocket, SIGNAL(readyRead()), this, SLOT(onSocketReadyRead()));
}
ExMulticast::~ExMulticast()
{
delete ui;
}
void ExMulticast::on_actStart_triggered()
{
QString ip = ui->comboBoxIp->currentText();
m_groupAddress = QHostAddress(ip);
quint16 port = ui->spinBoxBind->value();
if (m_udpSocket->bind(QHostAddress::AnyIPv4, port, QUdpSocket::ShareAddress)) { //绑定端口
m_udpSocket->joinMulticastGroup(m_groupAddress); //加入多播组
ui->plainTextEdit->appendPlainText("[用户:" + getLocalIp() +"] 加入组播(组播地址:" + ip + " 端口:" + QString::number(port) + ")成功");
ui->actStart->setEnabled(false);
ui->actStop->setEnabled(true);
} else {
ui->plainTextEdit->appendPlainText("[用户:" + getLocalIp() +"] 加入组播(组播地址:" + ip + " 端口:" + QString::number(port) + ")失败");
}
}
void ExMulticast::on_actStop_triggered()
{
m_udpSocket->leaveMulticastGroup(m_groupAddress); //退出组播
m_udpSocket->abort(); //解除绑定
ui->plainTextEdit->appendPlainText("[用户:" + getLocalIp() +"] 退出组播成功");
ui->actStart->setEnabled(true);
ui->actStop->setEnabled(false);
}
void ExMulticast::on_actClear_triggered()
{
ui->plainTextEdit->clear();
}
void ExMulticast::on_actQuit_triggered()
{
close();
}
void ExMulticast::onSocketStateChange(QAbstractSocket::SocketState socketState)
{
switch (socketState) {
case QAbstractSocket::UnconnectedState:
m_labSocketState->setText("socket状态UnconnectedState");
break;
case QAbstractSocket::HostLookupState:
m_labSocketState->setText("socket状态HostLookupState");
break;
case QAbstractSocket::ConnectingState:
m_labSocketState->setText("socket状态ConnectingState");
break;
case QAbstractSocket::ConnectedState:
m_labSocketState->setText("socket状态ConnectedState");
break;
case QAbstractSocket::BoundState:
m_labSocketState->setText("socket状态BoundState");
break;
case QAbstractSocket::ClosingState:
m_labSocketState->setText("socket状态ClosingState");
break;
case QAbstractSocket::ListeningState:
m_labSocketState->setText("socket状态ListeningState");
break;
default:
m_labSocketState->setText("socket状态其他未知状态...");
break;
}
}
void ExMulticast::onSocketReadyRead()
{
while (m_udpSocket->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(m_udpSocket->pendingDatagramSize());
QHostAddress peerAddr;
quint16 peerPort;
m_udpSocket->readDatagram(datagram.data(), datagram.size(), &peerAddr, &peerPort); //读取数据包,消息+来自的Ip和port
QString str = datagram.data();
QString peer = QString("[From: %1 %2] %3").arg(peerAddr.toString()).arg(QString::number(peerPort)).arg(str);
ui->plainTextEdit->appendPlainText(peer);
}
}
QString ExMulticast::getLocalIp()
{
QString hostName = QHostInfo::localHostName();
QHostInfo hostInfo = QHostInfo::fromName(hostName);
QString Ip = "";
if (hostInfo.addresses().isEmpty())
return 0;
foreach (QHostAddress addr, hostInfo.addresses()) {
if (addr.protocol() == QAbstractSocket::IPv4Protocol) {
Ip = addr.toString();
break;
}
}
return Ip;
}
void ExMulticast::on_btnSend_clicked()
{
quint16 port = ui->spinBoxBind->value();
QString msg = ui->lineEdit->text();
QByteArray datagram = msg.toUtf8();
m_udpSocket->writeDatagram(datagram, m_groupAddress, port);
// m_udpSocket->writeDatagram(datagram.data(), datagram.size(), m_groupAddress, port);
ui->plainTextEdit->appendPlainText("[multicst] " + msg);
ui->lineEdit->clear();
ui->lineEdit->setFocus();
}

View File

@ -0,0 +1,64 @@
/*
* Copyright (C) 2019 ~ 2019 touwoyimuli. All rights reserved.
*
* Author: touwoyimuli <touwoyimuli@gmai.com>
*
* github: https://github.com/touwoyimuli
* blogs: https://touwoyimuli.github.io/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://touwoyimuli.github.io/>.
*/
#ifndef EXMULTICAST_H
#define EXMULTICAST_H
#include <QMainWindow>
#include <QUdpSocket>
#include <QLabel>
#include <QHostInfo>
#include <QHostAddress>
namespace Ui {
class ExMulticast;
}
class ExMulticast : public QMainWindow
{
Q_OBJECT
public:
explicit ExMulticast(QWidget *parent = nullptr);
~ExMulticast();
private slots:
void on_actStart_triggered();
void on_actStop_triggered();
void on_actClear_triggered();
void on_actQuit_triggered();
void onSocketStateChange(QAbstractSocket::SocketState socketState); //socket 状态发生变化
void onSocketReadyRead(); //读取 socket 传入的数据
void on_btnSend_clicked();
private:
QString getLocalIp(); //获取本机IP
private:
Ui::ExMulticast *ui;
QUdpSocket* m_udpSocket; //用于通讯的 socket
QLabel* m_labSocketState;
QHostAddress m_groupAddress; //组播地址
};
#endif // EXMULTICAST_H

View File

@ -0,0 +1,55 @@
#-------------------------------------------------
#
# Project created by QtCreator 2019-12-04T21:34:23
#
#-------------------------------------------------
QT += core gui network
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = ExMulticast
TEMPLATE = app
# The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
CONFIG += c++11
SOURCES += \
main.cpp \
ExMulticast.cpp
HEADERS += \
ExMulticast.h
FORMS += \
ExMulticast.ui
macx {
ICON = images/icon.icns
}
unix:!macx{
# linux only
}
win32 {
RC_ICONS = images/icon.ico
}
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
RESOURCES += \
resources.qrc

View File

@ -0,0 +1,190 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ExMulticast</class>
<widget class="QMainWindow" name="ExMulticast">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>522</width>
<height>396</height>
</rect>
</property>
<property name="windowTitle">
<string>ExMulticast</string>
</property>
<widget class="QWidget" name="centralWidget">
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_4">
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>组播端口:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QSpinBox" name="spinBoxBind">
<property name="maximum">
<number>65000</number>
</property>
<property name="value">
<number>8888</number>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
<widget class="QLabel" name="label_3">
<property name="text">
<string>组播地址:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="comboBoxIp">
<property name="editable">
<bool>true</bool>
</property>
<property name="currentText">
<string>239.255.43.21</string>
</property>
<item>
<property name="text">
<string>239.255.43.21</string>
</property>
</item>
<item>
<property name="text">
<string>239.255.100.1</string>
</property>
</item>
<item>
<property name="text">
<string>239.255.255.100</string>
</property>
</item>
</widget>
</item>
</layout>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_5">
<item>
<widget class="QLineEdit" name="lineEdit"/>
</item>
<item>
<widget class="QPushButton" name="btnSend">
<property name="text">
<string>组播发送</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QPlainTextEdit" name="plainTextEdit">
<property name="plainText">
<string>239.0.0.0239.255.255.255为本地管理组播地址范围</string>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QMenuBar" name="menuBar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>522</width>
<height>25</height>
</rect>
</property>
</widget>
<widget class="QToolBar" name="mainToolBar">
<property name="toolButtonStyle">
<enum>Qt::ToolButtonTextBesideIcon</enum>
</property>
<attribute name="toolBarArea">
<enum>TopToolBarArea</enum>
</attribute>
<attribute name="toolBarBreak">
<bool>false</bool>
</attribute>
<addaction name="actStart"/>
<addaction name="actStop"/>
<addaction name="separator"/>
<addaction name="actClear"/>
<addaction name="separator"/>
<addaction name="actQuit"/>
</widget>
<widget class="QStatusBar" name="statusBar"/>
<action name="actStart">
<property name="icon">
<iconset resource="resources.qrc">
<normaloff>:/images/Image4.png</normaloff>:/images/Image4.png</iconset>
</property>
<property name="text">
<string>加入</string>
</property>
<property name="toolTip">
<string>加入组播</string>
</property>
</action>
<action name="actStop">
<property name="icon">
<iconset resource="resources.qrc">
<normaloff>:/images/Image5.png</normaloff>:/images/Image5.png</iconset>
</property>
<property name="text">
<string>退出</string>
</property>
<property name="toolTip">
<string>退出组播</string>
</property>
</action>
<action name="actClear">
<property name="icon">
<iconset resource="resources.qrc">
<normaloff>:/images/Image1.png</normaloff>:/images/Image1.png</iconset>
</property>
<property name="text">
<string>清空</string>
</property>
<property name="toolTip">
<string>清空文本内容</string>
</property>
</action>
<action name="actQuit">
<property name="icon">
<iconset resource="resources.qrc">
<normaloff>:/images/Image2.jpg</normaloff>:/images/Image2.jpg</iconset>
</property>
<property name="text">
<string>退出</string>
</property>
<property name="toolTip">
<string>退出程序</string>
</property>
</action>
</widget>
<layoutdefault spacing="6" margin="11"/>
<resources>
<include location="resources.qrc"/>
</resources>
<connections/>
</ui>

Binary file not shown.

After

Width:  |  Height:  |  Size: 603 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 352 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 803 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 468 B

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

View File

@ -0,0 +1,11 @@
#include "ExMulticast.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
ExMulticast w;
w.show();
return a.exec();
}

View File

@ -0,0 +1,8 @@
<RCC>
<qresource prefix="/">
<file>images/Image1.png</file>
<file>images/Image2.jpg</file>
<file>images/Image4.png</file>
<file>images/Image5.png</file>
</qresource>
</RCC>