12_UDP通信

一、普通udp通信

#include "UDPClient.h"


UDPClient::UDPClient( QWidget *parent ):QWidget( parent ) {

    cSocket = new QUdpSocket ;
    quint16 port = 8888 ;
    cSocket->bind( port ) ;
    connect( cSocket , SIGNAL( readyRead() ) , this , SLOT(slotReadyRead()) ) ;

    QTimer* timer = new QTimer(this);
    timer->setInterval(1000);
    timer->start();

    connect(timer, &QTimer::timeout, [&](){
        quint64 timestamp = QDateTime::currentMSecsSinceEpoch();
        QString str = QString::number(timestamp);
#if 1
        // 普通UDPsocket发送
        cSocket->writeDatagram(str.toUtf8(), QHostAddress("127.0.0.1"), 6666);
#else
        // 广播发送,注意:QHostAddress::Broadcast是255.255.255.255, 192.168.6.255
     //   cSocket->writeDatagram(str.toUtf8(), QHostAddress::Broadcast, 6666);

        //多播 multicast, 224.0.0.1~224.0.0.255 is multicast address of LAN
        cSocket->writeDatagram(str.toUtf8(), QHostAddress("224.0.0.131"), 6666);
#endif
    });
}


void UDPClient::slotReadyRead(){

    while( cSocket->hasPendingDatagrams() ) {
        quint32 datagramSize = cSocket->pendingDatagramSize();
        QByteArray buf(datagramSize, 0);
        cSocket->readDatagram(buf.data(), buf.size());
        qDebug() << "Udp2" <<buf;
    }
}


UDPClient::~UDPClient(void) { }
#include "UDPServer.h"


UDPServer::UDPServer( QWidget *parent ):QWidget(parent) {

    udpSocket = new QUdpSocket(this) ;
    quint16 port = 6666 ;
    udpSocket->bind( QHostAddress::LocalHost , port ) ;
    connect( udpSocket , SIGNAL( readyRead() ) , this , SLOT(slotReadyRead()) ) ;
    udpSocket->joinMulticastGroup(QHostAddress("224.0.0.131"));//只有加入多播的ip地址,才可以接收到多播服务发出来的信息

    QTimer *timer = new QTimer( this ) ;
    timer->setInterval(2000) ;
    timer->start() ;
    connect( timer , &QTimer::timeout , [&](){
        quint64 times = QDateTime::currentMSecsSinceEpoch() ;
        QString str = QString::number( times ) ;
        udpSocket->writeDatagram( str.toUtf8() , QHostAddress("127.0.0.1") , 8888 ) ;
    } ) ;
}
void UDPServer::slotReadyRead(){

    while( udpSocket->hasPendingDatagrams() ) {
        quint32 datagramSize = udpSocket->pendingDatagramSize();
        QByteArray buf(datagramSize, 0);
        udpSocket->readDatagram(buf.data(), buf.size());
        qDebug() <<"Udp1"<< buf;
    } 
}

UDPServer::~UDPServer(void) { }

二、多播、广播的区别

广播:只在局域网中使用,局域网中的每个电脑都能收到;
多播:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值