Qt UDP通讯

#pragma once
#include <QtWidgets/QWidget>
#include <QUdpSocket>		//UDP套接字
#include "ui_QtUdp.h"

class QtUdp : public QWidget
{
	Q_OBJECT

public:
	QtUdp(QWidget *parent = Q_NULLPTR);

private slots:
	void slotDealMsg();
	void slotSend();
	void slotClose();

private:
	Ui::QtUdpClass ui;
	QUdpSocket *udpSocket;
};
#include "QtUdp.h"
#include <QHostAddress>

QtUdp::QtUdp(QWidget *parent)
	: QWidget(parent)
{
	ui.setupUi(this);

	//分配空间,指定父对象
	udpSocket = new QUdpSocket(this);
	//绑定
	udpSocket->bind(8888);
	//udpSocket->bind(QHostAddress::AnyIPv4, 8888);
	//加入某个组播 组播地址是D类地址
	//udpSocket->joinMulticastGroup(QHostAddress("224.0.0.2"));
	//也可离开某个组播
	//udpSocket->leaveMulticastGroup(QHostAddress("224.0.0.2"));
	//当对方成功发送数据过来,会自动触发 readyRead() 信号
	//当对方成功发送数据过来,会自动触发 readyRead() 信号
	connect(udpSocket, &QUdpSocket::readyRead, this, &QtUdp::slotDealMsg);
	connect(ui.button_Send,&QPushButton::clicked,this,&QtUdp::slotSend);
	connect(ui.button_Close, &QPushButton::clicked, this, &QtUdp::slotClose);
}
void QtUdp::slotDealMsg()
{
	//读取对方发送的内容
	char buffer[1024] = { 0 };
	QHostAddress cliAddr;	//对方地址
	quint16 port;		//对方端口
	qint64 len = udpSocket->readDatagram(buffer,sizeof(buffer), &cliAddr, &port);
	if (len > 0)
	{
		QString str = QString::fromLocal8Bit("[%1:%2] %3").arg(cliAddr.toString()).arg(port).arg(buffer);
		//给编辑区设置内容
		ui.textEdit->setText(str);
	}
}
void QtUdp::slotSend()
{
	QString str = ui.textEdit->toPlainText();
	QString IP = ui.lineEdit_IP->text();
	quint16 port = ui.label_Port->text().toInt();
	//给指定的IP发送数据
	udpSocket->writeDatagram(str.toUtf8(), QHostAddress(IP),port);
}
void QtUdp::slotClose()
{
	udpSocket->disconnect();
	udpSocket->close();
}

相关推荐
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页