UDP客户端——UDP服务器
QT已封装好,使用里面的几个类可以进行简单的通信
服务器端代码
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(ui->pushButton,&QPushButton::clicked,this,&MainWindow::starBtnClicked);
port=5555;
isstart=false;
udpSockedt=new QUdpSocket(this);
timer=new QTimer(this);
connect(timer,&QTimer::timeout,this,&MainWindow::timeout);
//connect(timer,SIGNAL(QTimer::timeout()),this,SLOT(QTimer::timeout()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::starBtnClicked()
{
if(!isstart)
{
ui->pushButton->setText("停止");
timer->start(1000);
isstart=true;
}else {
ui->pushButton->setText("开始");
isstart=false;
timer->stop();
}
}
void MainWindow::timeout()
{
QString msg=ui->lineEdit->text();
int length=0;
if (msg=="")
{
qDebug() << "msg==""";
return;
}
if ((length=udpSockedt->writeDatagram(msg.toLatin1(),msg.length(),QHostAddress::Broadcast,port))!=msg.length())
{return;}
}
加上需要头文件以及QT+=network 将QT的网络模块添加到项目中
UDP客户端的代码
udpClient::udpClient(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::udpClient)
{
ui->setupUi(this);
setWindowTitle("UDP Client");
connect(ui->closeBtn,&QPushButton::clicked,this,&udpClient::CloseBtnClicked);
port=5555;
//isstart=false;
udpSocket=new QUdpSocket(this);
//timer=new QTimer(this);
connect(udpSocket,&QIODevice::readyRead,this,&udpClient::dataReceived);//readyRead信号是由QUdpsocket继承过来的
bool result=udpSocket->bind(port);
if (!result)
{
QMessageBox::information(this,"error","udp socket create error");
return;
}
}
udpClient::~udpClient()
{
delete ui;
}
void udpClient::CloseBtnClicked()
{
close();
}
void udpClient::dataReceived()
{
while(udpSocket->hasPendingDatagrams())
{
QByteArray datagram;
datagram.resize(udpSocket->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
// 读取数据报
udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
// 输出接收到的数据
qDebug() << "Received from" << sender.toString() << ":" << senderPort << "data:" << datagram;
ui->textEdit->insertPlainText(datagram.data());
ui->textEdit->insertPlainText(sender.toString());
}
}