qudpsocket是怎么用的

qudpsocket是怎么用的,第1张

  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);

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/dianzi/2705525.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-08-16
下一篇 2022-08-16

发表评论

登录后才能评论

评论列表(0条)

保存