全球最实用的IT互联网信息网站!

AI人工智能P2P分享&下载搜索网页发布信息网站地图

当前位置:诺佳网 > 电子/半导体 > 通信网络 >

qudpsocket是怎么用的

时间:2017-12-08 15:15

人气:

作者:admin

标签: qudpsocket 

导读:qudpsocket是怎么用的-UDP是无连接的不可靠的传输协议,可以用在可靠传输不是很重要的情况下使用。 QUdpSocket是QAbstractSocket 的子类,它们都继承了QIODevice。所以可以用QUdpSocket进行发送接...

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

温馨提示:以上内容整理于网络,仅供参考,如果对您有帮助,留下您的阅读感言吧!
相关阅读
本类排行
相关标签
本类推荐

CPU | 内存 | 硬盘 | 显卡 | 显示器 | 主板 | 电源 | 键鼠 | 网站地图

Copyright © 2025-2035 诺佳网 版权所有 备案号:赣ICP备2025066733号
本站资料均来源互联网收集整理,作品版权归作者所有,如果侵犯了您的版权,请跟我们联系。

关注微信