qt 实现udp c/s通信

如果您想在Qt中实现UDP客户端/服务器通信,可以使用Qt的网络模块,特别是QUdpSocket类。

以下是一个简单的UDP服务器示例:

#include 
#include 
#include 

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QUdpSocket *udpSocket = new QUdpSocket();
    udpSocket->bind(45454, QUdpSocket::ShareAddress);
    qDebug() << "UDP Server is running on port 45454";

    while (true) {
        while (udpSocket->hasPendingDatagrams()) {
            QByteArray datagram;
            datagram.resize(udpSocket->pendingDatagramSize());
            QHostAddress sender;
            quint16 senderPort;
            udpSocket->readDatagram(datagram.data(), datagram.size(),
                                    &sender, &senderPort);
            qDebug() << "Received message from" << sender.toString() << ":" << senderPort;
            qDebug() << "Message:" << datagram;
        }
    }

    return a.exec();
}

你可能感兴趣的:(qt,udp,c语言,开发语言,网络协议)