Add to:
QT += network
Import the header file:
#include<QUdpSocket>
step:
One: Create a socket object
Two: Bind your own port number
Three, send information
Four, receive information
Practice:
Create two windows, one called udp1 and one called udp2
The ip I gave to udp1: 127.0.0.1 , port (port): 9999
ip of udp2: 127.0.0.1, port: 8888
Write code udp1:
m_udp1 = new QUdpSocket(this);
//绑定自己的端口号
m_udp1->bind(ui->le_port->text().toInt());
//对方ip,对方端口
QString toIP = "127.0.0.1";
QString toPORT = "8888";
//点击发送按钮,发送报文
connect(ui->pushButton,&QPushButton::clicked,[=](){
// writeDatagram()是Qt中用于发送UDP数据包的函数
// 参数:
// QByteArray data:待发送的数据内容。
// qint64 size:data的大小。
// const QHostAddress &address:目标主机的IP地址。
// quint16 port:目标主机的端口号。
// 其中 qint64 size可以省略
//书写报文, 参数 : 1,书写内容 2,对方ip 3,对方端口
m_udp1->writeDatagram(ui->te_input->toPlainText().toUtf8(),QHostAddress(toIP),toPORT.toInt());
//清空输入框
ui->te_input->clear();
});
//接收数据
connect(m_udp1,&QUdpSocket::readyRead,[=](){
//获取到报文长度
qint64 size = m_udp1->pendingDatagramSize();
QByteArray array = QByteArray(size,0);
//读取报文
m_udp1->readDatagram(array.data(),size);
//将数据同步到聊天记录
ui->te_show->append(array);
});
Write code udp2:
m_udp2 = new QUdpSocket(this);
//绑定自己的端口号
m_udp2->bind(ui->le_port->text().toInt());
//对方ip,对方端口
QString toIP = "127.0.0.1";
QString toPORT = "9999";
//点击发送按钮,发送报文
connect(ui->pushButton,&QPushButton::clicked,[=](){
//书写报文, 参数 : 1,书写内容 2,对方ip 3,对方端口
m_udp2->writeDatagram(ui->te_input->toPlainText().toUtf8(),QHostAddress(toIP),toPORT.toInt());
//清空输入框
ui->te_input->clear();
});
//接收数据
connect(m_udp2,&QUdpSocket::readyRead,[=](){
//获取到报文长度
qint64 size = m_udp2->pendingDatagramSize();
QByteArray array = QByteArray(size,0);
//读取报文
m_udp2->readDatagram(array.data(),size);
//将数据同步到聊天记录
ui->te_show->append(array);
});