UDP通信.

在“.pro”文件中添加如下语句:
QT += network
在h头文件中包含相关头文件
#include <QUdpSocket>
在头文件中添加QUdpSocket的类成员变量与函数
private:
    QUdpSocket *udpSocket;;
    void dataSend();

private slots:
    void dataReceived();
在源文件cpp添加声明:
#include <QHostAddress>
在源文件cpp文件构造函数中添加如下语句:
udpSocket = new QUdpSocket(this); 
connect(udpSocket, SIGNAL(readyRead()), this, SLOT(dataReceived()));
//udpSocket->bind(8080);//如果是server端接收数据,需要调用bind指定端口
在源文件cpp添加dataReceived()槽函数的实现代码
void Widget::dataReceived()
{
 char buf[1024];
    while(udpSocket->hasPendingDatagrams())
    {
        memset(buf, 0, sizeof(buf));
                udpSocket->readDatagram(buf, sizeof(buf));
        QMessageBox::information(this, tr("data"), buf);
    }
}
在源文件cpp添加发送UDP数据的实现代码
void Widget::dataSend()
{
    QHostAddress *serverIP = new QHostAddress();
    serverIP->setAddress("127.0.0.1");
    char buf[1024];
    memset(buf, 0, sizeof(buf));
    strcpy(buf, "hello world
");
    udpSocket->writeDatagram(buf, strlen(buf), *serverIP , 8080);
    delete serverIP;

}
原文地址:https://www.cnblogs.com/shichuan/p/4497937.html