当前位置:网站首页>QT notes - qudpsocket of network communication
QT notes - qudpsocket of network communication
2022-07-22 18:11:00 【Cool breeze in the old street °】
UDP( User datagram protocol ), It's a light weight , unreliable , Datagram oriented , Connectionless Protocols . When the reliability of communication requirements is not important ( Data may be lost ), It can be used UDP signal communication
.pro Add a network module to the file QT += network
The header file :#include<QUdpSocket>
Important functions :
bind() // Server binding port
hasPendingDatagrams() // When data comes , At least one datagram needs to be read .
writeDatagram(const char *data, qint64 size, const QHostAddress &address, quint16 port) // Function to the specified address host And port port Send datagram datagram, Returns the number of bytes successfully sent , Datagrams should not be too long , Not more than 512Byte
readDatagram(char *data, qint64 maxSize, QHostAddress *address = nullptr, quint16 *port = nullptr)
pendingDatagramSize() // Function the size of the first datagram to be read Byte.
joinMulticastGroup() // Function to make socket Join a multicast group groupAddress.
leaveMulticastGroup() // Function to make socket Leave the multicast group groupAddress.
Design it. UI:
The server :
1. Binding port
m_udpSocket->bind(QHostAddress::AnyIPv4,8888);
2. Send a message and Read message
2.1 Send a message
// pick up information
QString sendStr = ui.sendTextEdit->toPlainText();
quint16 port = ui.portLineEdit->text().toInt();
QString ip = ui.IPlineEdit->text();
m_udpSocket->writeDatagram(sendStr.toUtf8(), QHostAddress(ip), port);
// Connect socket Read the message sent
connect(m_udpSocket, &QUdpSocket::readyRead, this, &QUdpTest::readValue);
2.2 Read message
while (m_udpSocket->hasPendingDatagrams())
{
QByteArray array;
//array.resize(m_udpSocket->bytesAvailable());
array.resize(m_udpSocket->pendingDatagramSize());
QHostAddress address;
quint16 port;
m_udpSocket->readDatagram(array.data(), array.size(),&address,&port);
qDebug() << QStringLiteral(" The size passed is :") << array.size();
// Read data stream with
//QDataStream read(&array, QIODevice::ReadOnly);
//Person p;
//read >> p.age >> p.score ;
//read.readRawData(p.name, sizeof(p.name));
//QString str = QString("%1 %2 %3").arg(QString::number(p.age)).arg(p.name).arg(QString::number(p.score));
qDebug() << array.data();
// Read the structure sent ( Strong transformation into the structure we need to transform )
Person* p = reinterpret_cast<Person*>(array.data());
QString str1 = QString(QLatin1String(p->name));
QString str = QString("%1 %2 %3").arg(QString::number(p->age)).arg(str1).arg(QString::number(p->score));
ui.recvTextEdit->setText(str);
}
client :
1. Binding port
m_socket->bind(QHostAddress::AnyIPv4,9999);
2. Send a message and Read message
2.1 Send a message
quint16 port = ui.portLineEdit->text().toInt();
QString ip = ui.IPLineEdit->text();
QString sendStr = ui.sendTextEdit->toPlainText();
Person p1;
strcpy(p1.name, "xm");
p1.age = 20;
p1.score = 60;
// Sending data streams
//QByteArray text_data;
//QDataStream write(&text_data, QIODevice::WriteOnly);
//write << p1.age << p1.score ;
//write.writeRawData(p1.name, 20);
//m_socket->writeDatagram(text_data, text_data.size(), QHostAddress(ip), port);
// Send the contents in the input box
//m_socket->writeDatagram(sendStr.toUtf8(),QHostAddress(ip), port);
//m_socket->writeDatagram(sendStr.toLocal8Bit(), sendStr.size(), QHostAddress(ip), port);
// Send structure
m_socket->writeDatagram(( char*)&p1, sizeof(Person), QHostAddress(ip), port);
qDebug() << QStringLiteral(" Size of data sent :") << sizeof(p1);
2.2 Read message
while (m_socket->hasPendingDatagrams())
{
QByteArray array;
//array.resize(m_socket->bytesAvailable());// Set the space size according to the readable data
array.resize(m_socket->pendingDatagramSize());
QHostAddress address;
quint16 port;
m_socket->readDatagram(array.data(), array.size(), &address, &port);
// Display Chinese without garbled code
ui.recvTextEdit->setText(QString::fromLocal8Bit(array.data()) );
}
3. Both client and server join multicast
UDP Multicast is a one-to-one communication mode between hosts , When multiple clients join a multicast group defined by a multicast address , The client sends to this multicast address and port UDP The datagram , Members of the group can receive .
m_socket->joinMulticastGroup(QHostAddress("224.0.0.100"));
Complete code :
QUdpTest.h
#pragma once
#include <QtWidgets/QWidget>
#include "ui_QUdpTest.h"
#include <QUdpSocket>
#include <QDebug>
class QUdpTest : public QWidget
{
Q_OBJECT
struct Person
{
char name[20];
int age;
int score;
Person()
{
memset(name, 0, 20);
age = 0;
score = 0;
}
};
public:
QUdpTest(QWidget *parent = Q_NULLPTR);
~QUdpTest();
public slots:
void readValue();
void on_sendBtn_clicked();
void on_delBtn_clicked();
private:
Ui::QUdpTestClass ui;
QUdpSocket* m_udpSocket;
};
QUdpTest.cpp
#include "QUdpTest.h"
#include <QDebug>
#include <QByteArray>
#include <QString>
#include <QLatin1String>
QUdpTest::QUdpTest(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
m_udpSocket = new QUdpSocket(this);
this->setWindowTitle(QStringLiteral(" The binding port number is :8888"));
// Binding port
m_udpSocket->bind(QHostAddress::AnyIPv4,8888);
m_udpSocket->joinMulticastGroup(QHostAddress("224.0.0.100"));
connect(m_udpSocket, &QUdpSocket::readyRead, this, &QUdpTest::readValue);
ui.recvTextEdit->setReadOnly(true);
}
QUdpTest::~QUdpTest()
{
}
void QUdpTest::readValue()
{
while (m_udpSocket->hasPendingDatagrams())
{
QByteArray array;
//array.resize(m_udpSocket->bytesAvailable());
array.resize(m_udpSocket->pendingDatagramSize());
QHostAddress address;
quint16 port;
m_udpSocket->readDatagram(array.data(), array.size(),&address,&port);
qDebug() << QStringLiteral(" The size passed is :") << array.size();
//QDataStream read(&array, QIODevice::ReadOnly); // Read data stream
//Person p;
//read >> p.age >> p.score ;
//read.readRawData(p.name, sizeof(p.name));
//QString str = QString("%1 %2 %3").arg(QString::number(p.age)).arg(p.name).arg(QString::number(p.score));
qDebug() << array.data();
Person* p = reinterpret_cast<Person*>(array.data());
QString str1 = QString(QLatin1String(p->name));
QString str = QString("%1 %2 %3").arg(QString::number(p->age)).arg(str1).arg(QString::number(p->score));
ui.recvTextEdit->setText(str);
}
}
void QUdpTest::on_sendBtn_clicked()
{
// pick up information
QString sendStr = ui.sendTextEdit->toPlainText();
quint16 port = ui.portLineEdit->text().toInt();
QString ip = ui.IPlineEdit->text();
m_udpSocket->writeDatagram(sendStr.toUtf8(), QHostAddress(ip), port);
}
void QUdpTest::on_delBtn_clicked()
{
m_udpSocket->leaveMulticastGroup(QHostAddress("224.0.0.100"));
}
QUdpTest1.h
#pragma once
#include <QWidget>
#include "ui_QUdpTest1.h"
#include <QUdpSocket>
class QUdpTest1 : public QWidget
{
Q_OBJECT
struct Person
{
char name[20];
int age;
int score;
Person()
{
memset(name, 0, 20);
age = 0;
score = 0;
}
};
public:
QUdpTest1(QWidget *parent = Q_NULLPTR);
~QUdpTest1();
public slots:
void readValue();
void on_sendBtn_clicked();
void on_delBtn_clicked();
private:
Ui::QUdpTest1 ui;
QUdpSocket* m_socket;
};
QUdpTest1.cpp
#include "QUdpTest1.h"
#include <string.h>
QUdpTest1::QUdpTest1(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
m_socket = new QUdpSocket(this);
this->setWindowTitle(QStringLiteral(" The binding port is :9999"));
m_socket->bind(QHostAddress::AnyIPv4,9999);
m_socket->joinMulticastGroup(QHostAddress("224.0.0.100"));
connect(m_socket, &QUdpSocket::readyRead, this, &QUdpTest1::readValue);
ui.recvTextEdit->setReadOnly(true);
}
QUdpTest1::~QUdpTest1()
{
}
void QUdpTest1::readValue()
{
while (m_socket->hasPendingDatagrams())
{
QByteArray array;
//array.resize(m_socket->bytesAvailable());// Set the space size according to the readable data
array.resize(m_socket->pendingDatagramSize());
QHostAddress address;
quint16 port;
m_socket->readDatagram(array.data(), array.size(), &address, &port);
ui.recvTextEdit->setText(array);
}
}
void QUdpTest1::on_sendBtn_clicked()
{
quint16 port = ui.portLineEdit->text().toInt();
QString ip = ui.IPLineEdit->text();
QString sendStr = ui.sendTextEdit->toPlainText();
Person p1;
strcpy(p1.name, "xm");
p1.age = 20;
p1.score = 60;
//QByteArray text_data;
//QDataStream write(&text_data, QIODevice::WriteOnly);
//write<< p1.age << p1.score ;
//write.writeRawData(p1.name, sizeof(p1.name));
//m_socket->writeDatagram(text_data, text_data.size(), QHostAddress(ip), port);
//m_socket->writeDatagram(sendStr.toUtf8(),QHostAddress(ip), port);
//m_socket->writeDatagram(sendStr.toLocal8Bit(), sendStr.size(), QHostAddress(ip), port);
m_socket->writeDatagram(( char*)&p1, sizeof(Person), QHostAddress(ip), port);
qDebug() << QStringLiteral(" Size of data sent :") << sizeof(p1);
}
void QUdpTest1::on_delBtn_clicked()
{
m_socket->leaveMulticastGroup(QHostAddress("224.0.0.100"));
}
Running results :
Send the content in the text :
Send the content in the structure :
Reference blog :
QT Network programming UDP
边栏推荐
- GBase8s数据库SET Database Object Mode 语句
- 日期类的理解学习
- 以SPI的仿真文件学习TB写法
- How to solve the gloomy life under the middle-aged crisis of it
- 力扣练习——24 去除重复字母
- GBase8s数据库以 SET COLLATION 指定对照顺序
- GBase8s数据库SET AUTOFREE 语句
- How to carry out efficient data governance? Index management and data traceability help!
- Calculate deposit interest
- GBase8s数据库UNION 运算符
猜你喜欢
随机推荐
OceanBase数据库搭建测试
24、 TF coordinate transformation (IV): multi coordinate transformation and coordinate system relationship view
并发模型值Actor和CSP
Bigder:35/100 development colleagues said that I tested it myself. But something went wrong after the launch.
[exception] generate guid and datetime, import test data to the database
go fmt包详解
vcs与verdi学习记录
力扣练习——31 有效的井字游戏
学IT,你后悔了么?
Excel import export controller
Dokcer运行Nacos容器自动退出问题
面向项目版本差异性的漏洞识别技术研究
异地多活的演变
mysql存储过程返回的结果集的问题
Union in gbase8s database subquery
在线XML转CSV工具
ieee下载文献的方法
Verilog基本语法(2)
Anaconda 环境迁移
Understanding and learning of arrays class