实现效果
实现过程
准备工作
在.pro中增加一句话
QT +=network
绘制界面
.h文件内容:
#ifndef WIDGET_H
#define WIDGET_H
#include "receivethread.h"
#include "sendthread.h"
#include <QWidget>
#include <QUdpSocket>
#include <iostream>
#include <stdint.h>
#include <sstream>
using namespace std;
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = nullptr);
~Widget();
public slots:
//接收信号
void receiveSlot();
//停止线程
void quitThreaSlot();
private slots:
void on_pushButton_clicked();
void on_pushButton_5_clicked();
void on_pushButton_4_clicked();
private:
Ui::Widget *ui;
receiveThread*preceiveTHread;
private:
QUdpSocket *m_udpSocket = nullptr;
};
#endif // WIDGET_H
构造函数内容
ui->setupUi(this);
preceiveTHread = new receiveThread(this);
//本地主机名
QString hostName = QHostInfo::localHostName();
//本机IP地址
QHostInfo hostInfo = QHostInfo::fromName(hostName);
//IP地址列表
QList<QHostAddress> addrList = hostInfo.addresses();
for(int i=0;i<addrList.count();i++)
{
QHostAddress host = addrList.at(i);
if(QAbstractSocket::IPv4Protocol == host.protocol())
{
QString ip = host.toString();
ui->comboBox->addItem(ip);
}
}
m_udpSocket = new QUdpSocket(this);
//连接信号和槽(绑定端口就开始接收信号线程,接收到数据就显示,关闭窗口关闭线程)
connect(this,SIGNAL(destroyed()),this,SLOT(quitThreaSlot()));
connect(preceiveTHread,SIGNAL(receiveSignal()),this,SLOT(receiveSlot()));
对于绑定按钮的定义函数:
void Widget::on_pushButton_clicked()
{
//本机UDP端口
qint16 port = ui->spinBox->value();
if(m_udpSocket->bind(port))
{
ui->plainTextEdit->appendPlainText("**已成功绑定");
ui->plainTextEdit->appendPlainText("**绑定端口: "+QString::number(m_udpSocket->localPort()));
ui->pushButton->setEnabled(false);
}
else
{
ui->plainTextEdit->appendPlainText("**绑定失败");
}
//启动线程
preceiveTHread->start();
}
接收信号的槽函数(UDP接收到数据显示)
void Widget::receiveSlot()
{
ui->lineEdit->clear();
//是否还有待读取的传入数据报
while(m_udpSocket->hasPendingDatagrams())
{
QByteArray data;
//返回待读取的数据报的字节数
data.resize(m_udpSocket->pendingDatagramSize());
QHostAddress peerAddr;
quint16 peerPort;
//读取数据报的内容
m_udpSocket->readDatagram(data.data(),data.size(),&peerAddr,&peerPort);
QString str = data.data();
QString peer = "[From ] +"+peerAddr.toString()+":"+QString::number(peerPort)+"] ";
ui->lineEdit->setText(peer+str);
}
}
quitThreaSlot函数:
void Widget::quitThreaSlot()
{
preceiveTHread->quit();
preceiveTHread->wait();
}
退出按钮定义:文章来源:https://www.toymoban.com/news/detail-831272.html
void Widget::on_pushButton_4_clicked()
{
preceiveTHread->terminate();
}
使用的receivethread.h就是将run函数重写(循环发送定义的信号延迟即可),在定义一个信号即可。
以上即功能的所有有错还请指出文章来源地址https://www.toymoban.com/news/detail-831272.html
到了这里,关于Qt进行UDP通讯,创建一个收线程这样可以进行接收数据的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!