QUdpSocket简单使用Demo(局域网内发送给所有客户端消息与接收)

先看一下效果:

(程序服务端在不断发送消息,接收端每隔2秒接收一次消息)

服务端和客户端都用到一个公共类:

UDPServerAndClient.h:

#ifndef UDPSERVERANDCLIENT_H
#define UDPSERVERANDCLIENT_H

#include <QObject>
#include <QUdpSocket>
#include <QTimer>

class UDPServerAndClient : public QObject
{
    Q_OBJECT
public:
    explicit UDPServerAndClient(QObject *parent = 0);

    void setServerInit();
    void setClientInit();
private slots:
    void onServerSendBroadcast();
    void onPendingDatagrams();
private:
    QUdpSocket udpSocketServer;
    QUdpSocket udpSocketClient;
    QTimer timer;
};
#endif // UDPSERVERANDCLIENT_H

UDPServerAndClient.cpp:

#include "udpserverandclient.h"
#include <QHostInfo>
#include <QDataStream>
#include <QDateTime>

UDPServerAndClient::UDPServerAndClient(QObject *parent) : QObject(parent)
{
}

void UDPServerAndClient::setServerInit()
{
    connect(&timer, SIGNAL(timeout()), this, SLOT(onServerSendBroadcast())); //定时发送
    timer.start(2000);
}

void UDPServerAndClient::setClientInit()
{
    udpSocketClient.bind(13999);   //建立监听
    connect(&udpSocketClient, SIGNAL(readyRead()), this, SLOT(onPendingDatagrams())); //接收准备
}

void UDPServerAndClient::onServerSendBroadcast()
{
    QByteArray datagram;
    QDataStream out(&datagram, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_5_6);
    out << QDateTime::currentDateTime() << QHostInfo::fromName(QHostInfo::localHostName()).addresses().last().toString();
    //发送主机可以用QHostAddress("127.0.0.1")替换
    udpSocketServer.writeDatagram(datagram, QHostAddress::Broadcast, 13999);  // UDP 发送数据
}

void UDPServerAndClient::onPendingDatagrams()
{
    QByteArray datagram;

    do{
        datagram.resize(udpSocketClient.pendingDatagramSize());
        udpSocketClient.readDatagram(datagram.data(), datagram.size());  //接收数据
    } while( udpSocketClient.hasPendingDatagrams() );

    QDateTime dateTime;
    QString lastIP;
    QDataStream in(&datagram, QIODevice::ReadOnly);
    in.setVersion(QDataStream::Qt_5_6);
    in >> dateTime >> lastIP;

    qDebug() <<"dateTime.date().toString():" << dateTime.date().toString()
             <<"ip:" << lastIP;
}

 

©️2020 CSDN 皮肤主题: 代码科技 设计师: Amelia_0503 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值