UDP is a connectionless, unreliable transport protocol that can be used when reliable transmission is not important. QUdpSocket is a subclass of QAbstractSocket that inherits from QIODevice. So you can use QUdpSocket to send and receive data. The biggest difference between it and QTcpSocket is that there is no need to establish a connection before sending data.
The following simple example demonstrates how to use QUdpSocket to communicate between the client and the server.
Server code:[cpp] view plain copy
1. class UDPServer: public QObject
2. {
3. Q_OBJECT
4. public:
5. UDPServer(QObject *parent = NULL);
6. ~UDPServer();
7. private slots:
8. void readPendingDatagrams();
9. private:
10. QUdpSocket *udpSocket;
11.
12. };
[cpp] view plain copy
1. UDPServer::UDPServer(QObject *parent /* = NULL */): QObject(parent)
2. {
3. udpSocket = new QUdpSocket(this);
4. udpSocket-"bind(QHostAddress::LocalHost, 7755);
5. cout ""Server is Running....." "endl;
6. connect(udpSocket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()));
7. }
8.
9. UDPServer::~UDPServer()
10. {
11.
12. }
13.
14. void UDPServer::readPendingDatagrams()
15. {
16. QHostAddress sender;
17. quint16 senderPort;
18. while (udpSocket-"hasPendingDatagrams())
19. {
20. QByteArray datagram;
21. datagram.resize(udpSocket-"pendingDatagramSize());
22. udpSocket-"readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
23. string strMes(datagram);
24. std::cout "strMes" "endl;
25. }
26. QString text = "hello...";
27. QByteArray datagram = text.toLocal8Bit();
28. udpSocket-"writeDatagram(datagram.data(), datagram.size(), sender, senderPort);
29. }
Description:
1. I am testing on my own machine, so the server address is localHost. which is
[cpp] view plain copy
udpSocket-"bind(QHostAddress::LocalHost, 7755);
2. Send back information to the client
[cpp] view plain copy
udpSocket-"writeDatagram(datagram.data(), datagram.size(), sender, senderPort);
Pin Header Connector,0.80Mm Header Connector,3.96Mm Pin Header Connector,Smt Vertical Type Connector
Shenzhen CGE Electronic Co.,Ltd , https://www.cgeconnector.com