UDP通信中单个套接字既是服务器又是客户端。
创建UDP套接字:
QUdpSocket *udpSocket;
udpSocket=new QUdpSocket(this);
绑定本地端口作为服务端口:
udpSocket->bind(port)解除绑定udpSocket->abort();
向指定ip和端口的主机发送数据报:
QString targetIP=ui->comboTargetIP->currentText(); //目标IPQHostAddress targetAddr(targetIP);quint16 targetPort=ui->spinTargetPort->value();//目标portQString msg=ui->editMsg->text();//发送的消息内容QByteArray str=msg.toUtf8();udpSocket->writeDatagram(str,targetAddr,targetPort); //发出数据报
广播消息:
quint16 targetPort=ui->spinTargetPort->value(); //目标端口QString msg=ui->editMsg->text();QByteArray str=msg.toUtf8();udpSocket->writeDatagram(str,QHostAddress::Broadcast,targetPort);
连接读取数据槽函数:
connect(udpSocket,SIGNAL(readyRead()),this,SLOT(onSocketReadyRead()));void MainWindow::onSocketReadyRead()
{//读取收到的数据报while(udpSocket->hasPendingDatagrams()){QByteArray datagram;datagram.resize(udpSocket->pendingDatagramSize());QHostAddress peerAddr;quint16 peerPort;udpSocket->readDatagram(datagram.data(),datagram.size(),&peerAddr,&peerPort);QString str=datagram.data();QString peer="[From "+peerAddr.toString()+":"+QString::number(peerPort)+"] ";ui->plainTextEdit->appendPlainText(peer+str);}
}