原创

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

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://shazhenyu.blog.csdn.net/article/details/53509011

先看一下效果:

(程序服务端在不断发送消息,接收端每隔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;
}

 

文章最后发布于: 2016-12-07 17:58:32
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 代码科技 设计师: Amelia_0503

分享到微信朋友圈

×

扫一扫,手机浏览