UDP是無連接的不可靠的傳輸協議,可以用在可靠傳輸不是很重要的情況下使用。 QUdpSocket是QAbstractSocket 的子類,它們都繼承了QIODevice。所以可以用QUdpSocket進行發送接收數據。它和QTcpSocket最大的區別也就是,發送數據之前不需要建立連接
以下簡單例子,演示了用QUdpSocket如何實現客戶端和服務端的通信。
服務端代碼:
[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. }
說明:
1. 我都是在自己的機器上測試,所以服務器地址都是localHost。即
[cpp] view plain copy
udpSocket-》bind(QHostAddress::LocalHost, 7755);
2. 給客戶端回發信息
[cpp] view plain copy
udpSocket-》writeDatagram(datagram.data(),datagram.size(),sender, senderPort);
評論