Qt udp socket用于进程间通信

简单协议可以使用:json + base64(有需要)


#ifndef UDPSOCKET_H
#define UDPSOCKET_H

#include <QObject>
#include <QMap>
#include <QHostAddress>
#include <functional>

class QUdpSocket;
class UdpSocket : public QObject
{
    Q_OBJECT
public:
    struct Address {
        Address() : port(0) { }
        Address(const QHostAddress &_host, int _port) : host(_host), port(_port) { }

        QHostAddress host;
        int port;
    };

    typedef std::function<void(quint64 number, const QByteArray &data)> ReveivedHandleFunc;

    explicit UdpSocket(QObject *parent = 0);
    void init(int port, int isServer, const ReveivedHandleFunc &func);
    void send(quint64 number, const QByteArray &data);

private slots:
    void slotReadPendingData();

private:
    void processTheDatagram(const QByteArray &data);

private:
    QUdpSocket *m_udp;
    int m_port;
    bool m_isServer;
    ReveivedHandleFunc m_receivedHandleFunc;
    quint64 m_number;
    QMap<quint64, Address> m_msg;
};

#endif // UDPSOCKET_H

#include "udpsocket.h"
#include <QHostAddress>
#include <QUdpSocket>

UdpSocket::UdpSocket(QObject *parent)
    : QObject(parent), m_udp(NULL), m_port(0), m_isServer(false), m_number(0)
{
}

void UdpSocket::init(int port, int isServer, const ReveivedHandleFunc &func)
{
    if (NULL == m_udp) {
        m_udp = new QUdpSocket(this);
        connect(m_udp, SIGNAL(readyRead()), this, SLOT(slotReadPendingData()));
        if (isServer) {
            m_udp->bind(QHostAddress::LocalHost, port);
        }
    }

    m_port = port;
    m_isServer = isServer;
    m_receivedHandleFunc = func;
}

void UdpSocket::send(quint64 number, const QByteArray &data)
{
    if (!m_udp) {
        return;
    }

    if (m_isServer) {
        if (m_msg.contains(number)) {
            Address address = m_msg[number];
            m_msg.remove(number);
            m_udp->writeDatagram(data, address.host, address.port);
        }
    } else {
        m_udp->writeDatagram(data, QHostAddress::LocalHost, m_port);
    }
}

void UdpSocket::slotReadPendingData()
{
    if (NULL == m_udp) {
        return;
    }

    while (m_udp->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(m_udp->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;
        if (m_udp->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort)  >= 0) {
            ++m_number;
            if (m_msg.size() > 3000) {
                m_msg.clear();
            }
            m_msg[m_number] = Address(sender, senderPort);
            if (m_receivedHandleFunc) {
                m_receivedHandleFunc(m_number, datagram);
            }
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值