,工程名为“udpone”,work模块,Baseclass选择QMainWindow。(说明:如果一些QtCreator版本没有添加模块一项,:QT+=network)(TextEdit),左边的那个的objectName改为为textSend,右边的那个的objectName改为textReceive,添加一个按钮,改其objectName为send,如下所示:#include<work>,添加public变量 QHostAddress*hostaddr1;和QHostAddress*hostaddr2;添加private变量 QUdpSocket*udpSocket1;和QUdpSocket*udpSocket2;添加私有槽函数:privateslots: voidsend(); voidreceive();,加入如下代码:(1)在构造函数中添加:udpSocket1=newQUdpSocket(this); udpSocket2=newQUdpSocket(this); hostaddr1=newQHostAddress(""); hostaddr2=newQHostAddress(""); boolconn=udpSocket1->bind(*hostaddr1,6666,QUdpSocket::ShareAddress);//监听本机上的6666端口,如果有消息到来,就会发送readyRead()信号。 if(!conn){ QMessageBoxbox; (tr("连接错误")); (); }else{ connect(udpSocket1,SIGNAL(readyRead()),this,SLOT(receive())); connect(ui->send,SIGNAL(clicked()),this,SLOT(send())); }(2)实现send函数:voidMainWindow::send(){ QMessageBoxbox; QStringtext=ui->textSend->toPlainText(); if(()==0){ (tr("请输入发送内容")); (); } udpSocket2->writeDatagram((),(),*hostaddr2,6665);// }(3)实现receive函数:voidMainWindow::receive(){ while(udpSocket1->hasPendingDatagrams()){
Qt网络应用----socket通信例子 来自淘豆网www.taodocs.com转载请标明出处.