分为发送端与接收端
接收端通过监听串口接收发送端发送的数据
发送端
senderdialog.h
#ifndef SENDERDIALOG_H
#define SENDERDIALOG_H
#include <QDialog>
#include <QUdpSocket>
#include <QTimer>
#include <QHostAddress>
namespace Ui {
class SenderDialog;
}
class SenderDialog : public QDialog
{
Q_OBJECT
public:
explicit SenderDialog(QWidget *parent = 0);
~SenderDialog();
private slots:
void on_pushButton_clicked();
void sendMessage();
private:
Ui::SenderDialog *ui;
QUdpSocket *udpSocket;
QTimer *timer;
int flag_t; //biaozhiwei
};
#endif // SENDERDIALOG_H
senderdialog.cpp
#include "senderdialog.h"
#include "ui_senderdialog.h"
SenderDialog::SenderDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SenderDialog)
{
ui->setupUi(this);
timer = new QTimer(this);
udpSocket = new QUdpSocket(this);
ui->pushButton->setText("Start");
flag_t = 0;
connect(timer , SIGNAL(timeout()),this,SLOT(sendMessage()));
}
SenderDialog::~SenderDialog()
{
delete ui;
}
void SenderDialog::on_pushButton_clicked()
{
if(flag_t == 0)
{
flag_t = 1;
ui->pushButton->setText("Stop");
timer->start(1000);
ui->msgEdit->setEnabled(false);
ui->portEdit->setEnabled(false);
}else{
flag_t = 0;
ui->pushButton->setText("Start");
timer->stop();
ui->msgEdit->setEnabled(true);
ui->portEdit->setEnabled(true);
}
}
void SenderDialog::sendMessage()
{
quint16 port = ui->portEdit->text().toShort();
QString msg = ui->msgEdit->text();
udpSocket->writeDatagram(msg.toUtf8(),QHostAddress::LocalHost ,port);
}
接收端
receiverdialog.h
#ifndef RECEIVERDIALOG_H
#define RECEIVERDIALOG_H
#include <QDialog>
#include <QUdpSocket>
#include <QHostAddress>
namespace Ui {
class ReceiverDialog;
}
class ReceiverDialog : public QDialog
{
Q_OBJECT
public:
explicit ReceiverDialog(QWidget *parent = 0);
~ReceiverDialog();
private slots:
void on_pushButton_clicked();
void receiveMessage();
private:
Ui::ReceiverDialog *ui;
QUdpSocket *udpsocket;
bool flag_t;
quint16 port;
};
#endif // RECEIVERDIALOG_H
receiverdialog.cpp
#include "receiverdialog.h"
#include "ui_receiverdialog.h"
ReceiverDialog::ReceiverDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::ReceiverDialog)
{
ui->setupUi(this);
flag_t = false;
udpsocket = new QUdpSocket(this);
}
ReceiverDialog::~ReceiverDialog()
{
delete ui;
}
void ReceiverDialog::on_pushButton_clicked()
{
if(flag_t == false){
flag_t =true;
ui->pushButton->setText("Stop");
ui->lineEdit->setEnabled(false);
port = ui->lineEdit->text().toShort();
bool res = udpsocket->bind(port);
if(res ==false)
{
qDebug()<<"bind false";
}
connect(udpsocket,SIGNAL(readyRead()),this,SLOT(receiveMessage()));
}else{
flag_t = false;
udpsocket->close();
ui->lineEdit->setEnabled(true);
ui->pushButton->setText("Start");
}
}
void ReceiverDialog:: receiveMessage()
{
if(udpsocket->hasPendingDatagrams())
{
QByteArray buf;
buf.resize(udpsocket->pendingDatagramSize());
udpsocket->readDatagram(buf.data(),buf.size());
ui->listWidget->addItem(buf);
ui->listWidget->scrollToBottom();
}
}