udpServer->bind(QHostAddress::Any,8040); //绑定通信端口
connect(udpServer,SIGNAL(readyRead()),this,SLOT(recvData())); //连接信号接收函数
(2)数据接收
//接收数据while (udpServer->hasPendingDatagrams()){QByteArray datagram; //定义接收的数组datagram.resize(udpServer->pendingDatagramSize()); //设置接收数组的大小udpServer->readDatagram(datagram.data(), datagram.size()); //读取数据QString s = datagram.data(); //分离出需要的数据ui->plainTextEdit->appendPlainText(s); //数据显示}
源代码:
#include "widget.h"#include "ui_widget.h"UdpServer::UdpServer(QWidget *parent) :QWidget(parent),ui(new Ui::Widget){
ui->setupUi(this);udpServer=new QUdpSocket(this); //创建套接字udpServer->bind(QHostAddress::Any,8040); //绑定通信端口connect(udpServer,SIGNAL(readyRead()),this,SLOT(recvData())); //连接信号接收函数}
UdpServer::~UdpServer(){
delete ui;}
//接收数据的函数void UdpServer::recvData(){
//接收数据while (udpServer->hasPendingDatagrams()){QByteArray datagram; //定义接收的数组datagram.resize(udpServer->pendingDatagramSize()); //设置接收数组的大小udpServer->readDatagram(datagram.data(), datagram.size()); //读取数据QString s = datagram.data(); //分离出需要的数据ui->plainTextEdit->appendPlainText(s); //数据显示}}
三:客户端的编写
(1),初始化操作
udpClient=new QUdpSocket(this);
(2)发送数据
QString s= "hello test";udpClient->writeDatagram(s.toLatin1(), s.length(), QHostAddress::Broadcast, 8040);
源代码:
#include "widget.h"#include "ui_widget.h"Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget){
ui->setupUi(this);udpClient=new QUdpSocket(this); //创建套接字}
Widget::~Widget(){
delete ui;}
//发送数据的函数void Widget::on_pushButton_clicked(){
QString s= ui->lineEdit->text();udpClient->writeDatagram(s.toLatin1(), s.length(), QHostAddress::Broadcast, 8040); //向指定的端口发送数据}
三:基于Qt5.9的项目源码
联系客服