qt UDPSocket 的使用

//MyUdpSocket.h

cpp 复制代码
#ifndef MYUDPSOCKET_H
#define MYUDPSOCKET_H
//#pragma once


#include "udp_global.h"

#include <string>
#include <set>

#include <QUdpSocket>
#include <QNetworkInterface>
#include <QObject>
#include <QList>


static std::set<std::string> get_system_ip_all()
{
    std::set<std::string> setIp;
    //QList<QHostAddress> ipList;
    QList<QNetworkInterface> allIFS = QNetworkInterface::allInterfaces();
    foreach (QNetworkInterface interface, allIFS)
    {
        if(     interface.flags() & QNetworkInterface::IsUp
        && !(   interface.flags() & QNetworkInterface::IsLoopBack)
                )
        {
            foreach (QNetworkAddressEntry entry, interface.addressEntries())
            {
                if(entry.ip().protocol() == QAbstractSocket::IPv4Protocol)
                {
                    //ipList.append(entry.ip());
                    setIp.insert(entry.ip().toString().toStdString());
                }
            }
        }
    }
    return setIp;
} // */

static bool isSelfIp(std::set<std::string>& mySetIp, std::string& senderStrIp)
{
    std::set<std::string>::iterator itIp = mySetIp.begin();
    while(itIp != mySetIp.end())
    {
        if(senderStrIp.find(*itIp) != std::string::npos)
        {
            return true;
        }
        itIp++;
    }
    return false;
}


class UDPSHARED_EXPORT MyUdpSocket : public QObject
{
    Q_OBJECT
public:
    MyUdpSocket (unsigned short portReceive, unsigned short _portSend = 0, QObject* parent = nullptr);
    virtual ~MyUdpSocket();

    void sendMsg (QByteArray baMsg, unsigned short _port = 0);
    void sendMsg(const char *data, qint64 len, unsigned short _port = 0);

public slots:
    void readyRead();
    //void slotMsg(char buf[], unsigned short len);

signals:
    void sigMsg(char buf[], unsigned short len);

private:
    QThread* m_thread;
    QUdpSocket* m_pUdpSocketReceive;
    QUdpSocket* m_pUdpSocketSend;
    std::set<std::string> m_setIp;
    unsigned short m_portReceive;
    unsigned short m_portSend;

};

#endif // MYUDPSOCKET_H

//MyUdpSocket .cpp

cpp 复制代码
#include "MyUdpSocket.h"
#include <QNetworkDatagram>

MyUdpSocket::MyUdpSocket (unsigned short _portReceive, unsigned short _portSend, QObject* parent):QObject(parent),
m_portReceive(_portReceive), m_portSend (_portSend)
{
    m_setIp = get_system_ip_all();
    m_pUdpSocketReceive = new QUdpSocket(this);
    if(m_portSend==0)
    {
        m_pUdpSocketSend = m_pUdpSocketReceive;
        m_portSend = m_portReceive;
    }
    else
    {
        m_pUdpSocketSend = new QUdpSocket(this);
    }

    m_pUdpSocketReceive->bind(m_portReceive, QUdpSocket::ReuseAddressHint);//广播//QudpSockst::8hareAddresg//接收
    connect(m_pUdpSocketReceive, &QUdpSocket::readyRead, this, &MyUdpSocket::readyRead);//接收



    /*/组播
    m_pUdpSocket->bind(QHostAddress::AnyIPv4, m_portSend, QUdpSocket::ReuseAddressHint);
    m_pUdpSocket->joinMulticastGroup(QHostAddress("10.66.1.90"));//*/
    //connect(this,&MyUdpSocket::sigMsg, this,&MyUdpSocket::slotMsg);

    //m_thread = new QThread();
    //m_pUdpSocket->moveToThread(m_thread);
    //this->moveToThread(m_thread);
    //m_thread->start();
}

MyUdpSocket::~MyUdpSocket()
{
    if(m_pUdpSocketReceive)
    {
        if(m_pUdpSocketReceive == m_pUdpSocketSend)
        {
            m_pUdpSocketSend = nullptr;
        }
        delete m_pUdpSocketReceive;
        m_pUdpSocketReceive = nullptr;
    }
    if(m_pUdpSocketSend)
    {
        delete m_pUdpSocketSend;
        m_pUdpSocketSend = nullptr;
    }
}

void MyUdpSocket::sendMsg(QByteArray baMsg, unsigned short _port)
{
    if (_port == 0) _port = m_portSend;
    m_pUdpSocketSend->writeDatagram(baMsg, QHostAddress::Broadcast, _port);//广播
    //m_pUdpSocket->writeDatagram(baMsg, QHostAddress("10.66. 1. 90"), _port);//组播
}

void MyUdpSocket::sendMsg(const char *data, qint64 len, unsigned short _port)
{
    if (_port == 0) _port = m_portSend;
    m_pUdpSocketSend->writeDatagram(data, len, QHostAddress::Broadcast, _port);//广播
    //m_pUdpSocket->writeDatagram(data, len, QHostAddress("10.66. 1. 90"), _port);//组播
}

void MyUdpSocket::readyRead()
{
    if(m_pUdpSocketReceive->hasPendingDatagrams())
    {
        qint64 len = m_pUdpSocketReceive->pendingDatagramSize();
#if 0
        QHostAddress sendAddress;
        qint64 sendPort;
        QByteArray recvData;
        recvData.resize(len);
        m_pUdpSocketReceive->readDatagram(recvData.data(), len, &sendAddress, &sendPort);
#else
        QNetworkDatagram aa = m_pUdpSocketReceive->receiveDatagram(len);
        QHostAddress sendAddress = aa.destinationAddress();
        //qint64 sendPort = aa.destinationPort();
        QByteArray recvData = aa.data();
#endif
        std::string strSender = sendAddress.toString().toStdString();
        if(isSelfIp(m_setIp, strSender))   //接受到自己的数据
        {
            //int aa = 0;
            emit sigMsg(recvData.data(), len);
        }
        else    //接受到别人的数据
        {
            emit sigMsg(recvData.data(), len);
        }
    }
}

//void MyUdpSocket::slotMsg(char buf[], unsigned short len)
//{
//    //int a = 0;
//}

使用

cpp 复制代码
    m_pMyUdpSocket = new MyUdpSocket(1122,1133);
    connect(m_pMyUdpSocket, &MyUdpSocket::sigMsg, this, &MainWindow::onReadyRead);

    
    m_pMyUdpSocket->sendMsg(QByteArray("66666"),1133);
    m_pMyUdpSocket->sendMsg(QByteArray("44444"),1122);
相关推荐
程序喵大人1 小时前
【C++入门】编译链接模型 - 01 一个 C++ 程序是怎样变成可执行文件的
开发语言·c++·编译链接模型
by209992 小时前
vector 的模拟实现:扩容与边界的详细阐述(下)
c++·经验分享·vector·动态数组
ShyanZh3 小时前
【Python3基础】19-Socket 与 TCP、UDP 编程
python·网络协议·tcp/ip·udp
余额瞒着我当琳5 小时前
红黑树的实现--红黑树的概念、规则、效率、结构、旋转、查找、验证
数据结构·c++·算法
青少儿编程课堂5 小时前
AC自动机多模式串匹配精讲:校园关键词巡检实战解析
c++·python·算法·bfs·信息学竞赛
longlongzihan6 小时前
LeetCode 5. 最长回文子串:从暴力匹配到中心扩展的思维演进
c++·算法·leetcode
多弗朗皮卡丘6 小时前
C++继承
c++·继承
汉克老师7 小时前
GESP2026年9月认证C++七级( 第三部分编程题(2、括号序列))精讲
c++·gesp·小学生·学c++编程
流浪0018 小时前
计算机网络篇3:端口号与 socket:数据到达主机后,如何找到目标进程?
计算机网络·udp·tcp·端口·网络字节序
jimy19 小时前
虚函数vtable,链接时看到构造函数,linker把符号地址写入vtable(三)
开发语言·c++