Qt实现UDP通信

简述

本文用UdpReciver类实现UDP数据包接收,用UdpSender类实现UDP数据发送。

代码之路

UdpSend类头文件如下:

//UdpSend.h
# include <QUdpSocket>
class UdpSender : public QObject
{
	Q_OBJECT
public:
	UdpSender();
	~UdpSender();
	void initSender(QString desHost, int port);
	void send(QByteArray msg);
public slots:
	void recMsg(QByteArray msgInfo);
private:
	QUdpSocket *m_Socket = NULL;
	QString m_address;
	int m_port;
}

UdpSend类源文件如下:

UdpSender::UdpSender()
{
	m_Socket = new QUdpSocket();
	initSender("255.255.255.255", 8194);
}
UdpSender::~UdpSender()
{
	if (m_Socket != NULL)
	{
		delete m_Socket;
		m_Socket = NULL;
	}
}
void UdpSender::initSender(QString desHost, int port)
{
	m_address = desHost;
	m_port = port;
}
void UdpSender::send(QByteArray msg)
{
	m_Socket->writeDatagram(msg, QHostAddress(m_address), m_port);
}
void UdpSender::recMsg(QByteArray msgInfo)
{
	send(msgInfo);
}

UdpReciver类的头文件如下:

class UdpReciver : public QObject
{
	Q_OBJECT
public:
	UdpReciver(QObject *parent = NULL);
	~UdpReciver();
	void init_port(QString tmphost, int tmport);
signals:
	void deliverInfo(QByteArray info, QString clientip);
public slots:
	void readDatagrams(); //listen UDP data
private:
	QUdpSocket *m_udpSocket;
	QString m_localhost;
	int m_port;
	QByteArray m_data;
	QThread *m_thread;
};

UdpReciver类的源文件如下:

UdpReceiver::UdpReciver(QObject *parent) : QObject(parent)
{
	m_thread = new QThread();
	m_udpSocket = new QUdpSocket();
	QString localhost = "";
	init_port(localhost, 8192);
	connect(m_udpSocket, SIGNAL(readyRead()), this, SLOT(readDatagrams()), Qt::DirectConnection);
	this->moveToThread(m_thread);
	m_udpSocket->moveToThread(m_thread);
	m_thread->start();
}
UdpReciver::~UdpReciver()
{
	m_thread->quit();
	m_thread->wait();
	m_thead->deleteLater();
	m_udpSocket->close();
	m_udpSocket->deleteLater();
}
void UdpReciver::init_port(QString tmphost, int tmport)
{
	m_port = tmport;
	m_localhost = tmphost;
	m_udpSocket->bind(QHostAddress(m_localhost), m_port);
}
void UdpReciver::readDatagrams()
{
	QHostAddress client_address; //client ip addr
	m_data.clear();
	while(m_udpSocket->hasPendingDatagrams())
	{
		m_data.resize(m_udpSocket->pendingDatagramSize());
		m_udpSocket->readDatagram(m_data.data(), m_data.size(), &client_address);
		QString strclient_address = client_address.toString();
		deliverInfo(m_data, strclient_address);
		qDebug() << "receive UDP's size:“ << m_data.size();
	}
}

总结

UDP发送接收模块也可以整合在一个类中。为了灵活使用,这里使用两个类来分别接收和发送UDP数据。

发布了47 篇原创文章 · 获赞 45 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/lusanshui/article/details/88567424