QT UDP

1、UDP

对于UDP通信,我分为发送端可接收端。向指定ip的端口发送信息。

注意:在.pro文件中要添加QT += network,否则无法使用Qt的网络功能

发送端:

#include <QtNetWork>
QUdpSocket *sender;
sender = new QUdpSocket(this);
QByteArray datagram = "hello C++";
//UDP广播 writeDatagram(消息, 消息大小, 目标IP, 目标IP端口) 失败返回-1,成功返回消息长度
sender->writeDatagram(datagram.data(),datagram.size(),QHostAddress::Broadcast,port);
//向特定IP发送
QHostAddress serverAddress = QHostAddress("127.0.0.1");
sender->writeDatagram(datagram.data(), datagram.size(),serverAddress, port);


接收端:

xxx.h

#include <QtNetwork>
//信号槽
private slots:  
    void Rec(); 
private:
    QUdpSocket *receiver;

xxx.cpp

receiver = new QUdpSocket(this);
//bind(IP地址, 监听的端口)  成功返回true,失败返回false
receiver->bind(QHostAddress::LocalHost, port);
connect(receiver, SIGNAL(readyRead()),this, SLOT(Rec()));

void Rec()
 {
     while (receiver->hasPendingDatagrams()) 
     {
         QByteArray datagram;
         datagram.resize(receiver->pendingDatagramSize());
         receiver->readDatagram(datagram.data(), datagram.size());
         //datagram就是接受到的数据
     }
 }


相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页