qt

qt的udp数据发送与接收怎么实现

小亿
130
2024-02-29 09:36:19
栏目: 编程语言

在Qt中实现UDP数据发送与接收需要使用QUdpSocket类。以下是一个简单的示例代码:

// 创建一个QUdpSocket对象
QUdpSocket *udpSocket = new QUdpSocket(this);

// 绑定本地端口用于接收数据
udpSocket->bind(QHostAddress::Any, 1234);

// 发送数据
udpSocket->writeDatagram("Hello UDP", QHostAddress::LocalHost, 1234);

// 接收数据
connect(udpSocket, &QUdpSocket::readyRead, this, [=](){
    QByteArray datagram;
    datagram.resize(udpSocket->pendingDatagramSize());
    QHostAddress sender;
    quint16 senderPort;

    udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);

    qDebug() << "Received datagram: " << datagram;
    qDebug() << "From: " << sender.toString() << ":" << senderPort;
});

在上面的代码中,首先创建了一个QUdpSocket对象udpSocket,并绑定了本地端口1234用于接收数据。然后通过writeDatagram方法发送数据到本地主机的1234端口。接着通过连接readyRead信号来接收数据,从pendingDatagramSize()获取数据大小,readDatagram方法读取数据,并打印出接收到的数据以及发送方的IP地址和端口号。

0
看了该问题的人还看了