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();
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值