qt的udp数据发送与接收怎么实现
在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地址和端口号。
版权声明
本文仅代表作者观点,不代表米安网络立场。
上一篇:租用美国云主机怎么样 下一篇:如何通过高性能数据库提升Go语言网站的访问速度
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。