欢迎来到天天文库
浏览记录
ID:37899648
大小:26.00 KB
页数:5页
时间:2019-06-02
《QT UDP SOCKET编程》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、QT建立控制台项目,还是用最简单的c/s模式.client端:UDPclient.h #ifndefUDP_UDPclient_H#defineUDP_UDPclient_H#include#include#include#pragmaonce classUDPclient:publicQObject{ Q_OBJECT public: voidInitSocket();privateslots: voidRecv();};#e
2、ndifUDPclient.cpp #include"UDPclient.h"QUdpSocket *udpSocket; //套接字对象voidUDPclient::InitSocket(){ udpSocket=newQUdpSocket(this); udpSocket->bind(QHostAddress::Any,2002); connect(udpSocket,SIGNAL(readyRead()), this,SLOT(Recv()));}voidUDPclient::Recv(){ while(u
3、dpSocket->hasPendingDatagrams()) { QByteArraydatagram; datagram.resize(udpSocket->pendingDatagramSize()); udpSocket->readDatagram(datagram.data(),datagram.size()); for(inti=0;i4、atagram.at(i)); } printf(""); }}函数解释:pendingDatagramSize 当有数据包读入时返回true. resize为datageam设置大小 pendingDatagramSize返回udosocket第一个数据包的大小 readDatagram读数据包 server端,顺便学习写下个多进程QThread:main.cpp #include#include"UDP_QT.h"intma5、in(intargc,char*argv[]){ UDP_QTServer; QCoreApplicationa(argc,argv); Server.InitSocket(); Server.start();//进程开始 returna.exec();}UDP_QT.h #ifndefUDP_QT_H#defineUDP_QT_H#include#include#include#pragmaonce classUDP_QT6、:publicQThread{private: voidSend();public: voidInitSocket(); voidrun();};#endif UDP_QT.cpp #include"UDP_QT.h"QUdpSocket *udpSocket; //套接字对象charToAddress[20]="10.144.123.237";voidUDP_QT::InitSocket(){ udpSocket=newQUdpSocket(this);}voidUDP_QT::Send(){ charinfo7、rmation[]="adg"; while(1) { udpSocket->writeDatagram(information,QHostAddress(ToAddress),2002); printf("senddatagram:"); for(inti=0;i8、p函数要在进程下才能使用,它继承QThread }}voidUDP_QT::run()//运行进程{ Send();}
4、atagram.at(i)); } printf(""); }}函数解释:pendingDatagramSize 当有数据包读入时返回true. resize为datageam设置大小 pendingDatagramSize返回udosocket第一个数据包的大小 readDatagram读数据包 server端,顺便学习写下个多进程QThread:main.cpp #include#include"UDP_QT.h"intma
5、in(intargc,char*argv[]){ UDP_QTServer; QCoreApplicationa(argc,argv); Server.InitSocket(); Server.start();//进程开始 returna.exec();}UDP_QT.h #ifndefUDP_QT_H#defineUDP_QT_H#include#include#include#pragmaonce classUDP_QT
6、:publicQThread{private: voidSend();public: voidInitSocket(); voidrun();};#endif UDP_QT.cpp #include"UDP_QT.h"QUdpSocket *udpSocket; //套接字对象charToAddress[20]="10.144.123.237";voidUDP_QT::InitSocket(){ udpSocket=newQUdpSocket(this);}voidUDP_QT::Send(){ charinfo
7、rmation[]="adg"; while(1) { udpSocket->writeDatagram(information,QHostAddress(ToAddress),2002); printf("senddatagram:"); for(inti=0;i8、p函数要在进程下才能使用,它继承QThread }}voidUDP_QT::run()//运行进程{ Send();}
8、p函数要在进程下才能使用,它继承QThread }}voidUDP_QT::run()//运行进程{ Send();}
此文档下载收益归作者所有