前言
UDP不分客户端和服务端,
只使用一个类QUdpSocket。
提示:篇幅问题本文只提供部分代码,下面案例可供参考
一、 widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
udpSocket = new QUdpSocket(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::readyRead_Slot()
{
while(udpSocket->hasPendingDatagrams()){
QByteArray array;
array.resize(udpSocket->pendingDatagramSize());
udpSocket->readDatagram(array.data(),array.size());
QString buf;
buf = array.data();
ui->recvEdit->appendPlainText(buf);
}
}
void Widget::on_openBt_clicked()
{
if(udpSocket->bind(ui->localPort->text().toUInt()) == true)
{
QMessageBox::information(this,"提示","成功");
}else{
QMessageBox::information(this,"提示","失败");
}
connect(udpSocket,SIGNAL(readyRead()),this,SLOT(readyRead_Slot()));
}
void Widget::on_sendBt_clicked()
{
quint16 port;
QString sendbuff;
QHostAddress address;
address.setAddress(ui->aimIp->text());
sendbuff = ui->sendEdit->text();
port = ui->aimPort->text().