You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
1.6 KiB

2 years ago
#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
#include <QHostAddress>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
//1.创建对象
udpSocket = new QUdpSocket(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_btnOpen_clicked()
{
//2.打开连接
//判断是否成功
if(udpSocket->bind(ui->editLocalPort->text().toUInt()) == true){
QMessageBox::information(this,"提示","成功");
}else{
QMessageBox::critical(this,"提示","失败");
};
//3.连接成功触发函数
connect(udpSocket,SIGNAL(readyRead()),this,SLOT(readyRead()));
}
void Widget::readyRead(){
//3.槽函数,读取数据
while(udpSocket->hasPendingDatagrams()){ //判断是否有数据
QByteArray ary;
ary.resize(udpSocket->pendingDatagramSize());
udpSocket->readDatagram(ary.data(),ary.size());
QString buff;
buff = ary.data();
ui->editMessageRCV->appendPlainText(buff);
}
}
void Widget::on_btnSend_clicked()
{
//4.发送数据
//数据
QString sendBuff;
sendBuff = ui->editMessageSend->text();
//ip
QHostAddress addr;
addr.setAddress(ui->editTargetIP->text());
//端口
quint16 port;
port = ui->editTargetPort->text().toUInt();
//发送数据
udpSocket->writeDatagram(sendBuff.toLocal8Bit().data(),sendBuff.length(),addr,port);
}
void Widget::on_btnClose_clicked()
{
//5.关闭
udpSocket->close();
QMessageBox::information(this,"提示","已关闭");
}