Qt之局域网UDP通讯

时间:2022-12-15 14:08:44

创建两个QUdpSocket对象,一个用来发送数据,一个用来接收数据。发送数据的QUdpSocket需要绑定本机IP和端口,要不然是收不到数据的。

界面最上面的IP输入框是发送到的对方IP地址。中间是显示收到数据。下面的输入框是用来发送数据的。

在虚拟机中和本机通讯:

Qt之局域网UDP通讯

Qt没有IP输入框,需要自己去封装,也可以网上下载。我前面也发了一个自己封装的IP输入框,功能大部分和Windows IP输入框差不多,个别地方需要微修改一下。

主要程序:


#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QtNetwork>
#include <QLineEdit>
#include <QPushButton>

class CIPLineEdit;
namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();

private:
Ui::MainWindow *ui;

CIPLineEdit *m_pIPLineEdit;

QUdpSocket *m_rcvSocket;
QUdpSocket *m_sendSocket;
private slots:
void send();
void receive();
};

#endif // MAINWINDOW_H
#include "mainwindow.h"#include "ui_mainwindow.h"#include <QtNetwork>#include <QTextCodec>#include "iplineedit.h"MainWindow::MainWindow(QWidget *parent) :    QMainWindow(parent),    ui(new Ui::MainWindow){    ui->setupUi(this);    MainWindow::setWindowTitle(tr("UDP"));    m_pIPLineEdit = new CIPLineEdit(this);    m_pIPLineEdit->setGeometry(45, 25, 120, 26);	m_rcvSocket = new QUdpSocket(this);	ui->label_IP->setText("ToIP");	QString ipAddress;	QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();	for (int i = 0; i < ipAddressesList.size(); ++i)	{		if (ipAddressesList.at(i) != QHostAddress::LocalHost &&	ipAddressesList.at(i).toIPv4Address())		{			ipAddress = ipAddressesList.at(i).toString();			break;		}	}	bool conn = m_rcvSocket->bind(QHostAddress(ipAddress), 6660, QUdpSocket::ShareAddress);	if (!conn)		conn = m_rcvSocket->bind(QHostAddress("127.0.0.1"), 6660, QUdpSocket::ShareAddress);	if (conn)	{		connect(ui->send, SIGNAL(clicked()), this, SLOT(send()));		connect(m_rcvSocket, SIGNAL(readyRead()), this, SLOT(receive()));	}    m_sendSocket = new QUdpSocket(this);}MainWindow::~MainWindow(){    delete ui;}//发送消息void MainWindow::send(){	QString qs = ui->textSend->toPlainText();	QTextCodec *codec = QTextCodec::codecForName("GB2312");	QByteArray byte = codec->fromUnicode(qs);	if (qs.isEmpty())		return;	m_sendSocket->writeDatagram(byte.data(), byte.length(), QHostAddress(m_pIPLineEdit->GetIP()), 6660);	ui->textSend->clear();}//接收消息并显示void MainWindow::receive(){    QHostAddress addr;    quint16 port;    while(m_rcvSocket->hasPendingDatagrams())    {        QByteArray qb;		qb.resize(m_rcvSocket->pendingDatagramSize());		m_rcvSocket->readDatagram(qb.data(), qb.size(), &addr, &port);        QTextCodec *codec = QTextCodec::codecForName("GB2312");        QString str = codec->toUnicode(qb);		QString qStrIP = addr.toString();		if (qb.size())        {            ui->textReceive->append(qStrIP + " said:\n");            ui->textReceive->insertPlainText(str);        }    }}
qq:1245178753
本文地址: http://blog.csdn.net/u011417605/article/details/52515562

源码下载:http://download.csdn.net/detail/u011417605/9628682