当前位置:网站首页>Network connection mode of QT
Network connection mode of QT
2022-07-02 03:29:00 【AlbertOS】
introduce
Qt Support a wide range of network communication methods , Include HTTP/TP agreement 、TCP Connect 、UDP Connection and so on , Can be in Qt netWork
Module implementation ;
stay .pro
Add to file QT += network
You can use this module directly
and Qt It's supporting C++11 The original writing of , therefore C++ Many native libraries can also be used , You can even write directly socket
Connect ;
network Layout of module classes
Namespace :
name | explain |
---|---|
QPasswordDigestor | Contains functions that can be used to generate hashes or keys |
QSsl | Statement Qt All in the network SSL Class generic enumeration |
Members of the class :
name | explain |
---|---|
QAbstractNetworkCache | Interface of cache implementation |
QAbstractSocket | Basic functions common to all socket types |
QAuthenticator | Authentication object |
QDns | Domain name record , Store information about domain name records |
QDnsHostAddressRecord | Store information about host address records |
QDnsLookup | Express DNS lookup |
QDnsMailExchangeRecord | Storage is about DNS MX Recorded information |
QDnsServiceRecord | Storage is about DNS SRV Recorded information |
QDnsTextRecord | Storage is about DNS TXT Recorded information |
QDtls | These are UDP Sockets provide encryption |
QDtlsClientVerifier | This class implements server side DTLS Cookie Generate and verify |
QDtls | Such definition DTLS Cookie Parameters of the generator |
QHost Address | IP Address |
QHostInfo | Static function for hostname lookup |
QHstsPolicy | Specify host support HTTP Strict transmission security policy (HSTS) |
QHttp2 To configure | control HTTP/2 Parameters and settings |
QHttpMultiPart | Similar to passing HTTP Sent MIME Multipart messages |
QHttpPart | Save to HTTP Many parts MIME The body part used in the message |
QLocalServer | Local socket based server |
QLocalSocket | Local socket |
QNetworkAccessManager | Allow applications to send network requests and receive replies |
QNetworkAddressEntry | One supported by storage network interface IP Address and its associated netmask and broadcast address |
QNetworkCacheMetaData | Cache information |
QNetworkCookie | Save a network Cookie |
QNetworkCookieJar | A simple QNetworkCookie Object tank |
QNetworkDatagram | UDP Datagram data and metadata |
QNetworkDiskCache | Very basic disk cache |
QNetworkInterface | The host IP List of addresses and network interfaces |
QNetworkProxy | Network layer proxy |
QNetworkProxyFactory | Fine grained proxy selection |
QNetworkProxyQuery | Proxy settings for querying sockets |
QNetworkReply | Include use QNetworkAccessManager The data and header of the request sent |
QNetworkRequest | Save to use QNetworkAccessManager Sent request |
QOcspResponse | This class represents the online certificate status protocol response |
QSctpServer | be based on SCTP Server for |
QSctpSocket | SCTP Socket |
QSslCertificate | be used for X509 Convenience of certificates API |
QSslCertificateExtension | Used to access the X509 Certificate extended API |
QSslCipher | Express SSL Encrypted password |
QSslConfiguration | preservation SSL Configuration and status of the connection |
QSslDiffieHellmanParameters | For the server Diffie-Hellman Parameter interface |
QSslEllipticCurve | Represents the elliptic curve used by elliptic curve cryptography |
QSslError | Interrupter error |
QSslKey | Private key and public key interface |
QSslPreSharedKeyAuthenticator | Pre shared key (PSK) Authentication data of Password Suite |
QSslSocket | Client and server SSL Encrypted socket |
QTcpServer | be based on TCP Server for |
QTcpSocket | TCP Socket |
QUdpSocket | UDP Socket |
although Qt So many classes are provided for us to use , But we won't use so many interface classes in actual projects , There is no need to memorize it , Check it when you use it , There are only a few that are often used ,
Next, let's take a look at the general usage methods and several commonly used interface classes .
Network interface information acquisition
QNetwork Provide Q H o s t I n f o QHostInfo QHostInfo Class provides static functions , Search the host name , Use OS The lookup mechanism provided gets a IP Address or get a IP The host name associated with the address
QHostInfo Static functions in f r o m N a m e ( ) fromName() fromName()( Will block and return QHostInfo An object , Of this object address Function can get its host's IP Address list )
And l o o k u p H o s t lookupHost lookupHost( Asynchronous acquisition , It sends a signal every time it finds the host ) You can obtain host information
The main application code is as follows :
//QHostInfo Get hostname lookup
QString localHostName = QHostInfo::localHostName();// Got the local hostname
// By getting the hostname Then get it in two ways IP Address
//fromName Looking for host information
QHostInfo info = QHostInfo::fromName(localHostName);
info.addresses();// Get the host name related IP Address list Contains ipv4 And ipv6
//lookupHost lookup IP Address
QHostInfo::lookupHost(localHostName, this, SLOT(lookedUp(QHostInfo)));
void MainWindow::lookedUp(const QHostInfo &host) // Corresponding slot function
{
if (host.error() != QHostInfo::NoError) {
// First determine whether there is an error
qDebug() << "Lookup failed:" << host.errorString();
return;
}
foreach (const QHostAddress &address, host.addresses()) // Get address
qDebug() << "Found address:" << address.toString();
}
Provides Q N e t w o r k I n t e r f a c e QNetworkInterface QNetworkInterface Class to get the IP Address list and network interface information .
Q N e t w o r k I n t e r f a c e QNetworkInterface QNetworkInterface Class represents the network interface of the host running the current program
// Get a list of all network interfaces
QList<QNetworkInterface> list = QNetworkInterface::allInterfaces();
// Traverse every network interface
foreach (QNetworkInterface interface, list)
{
// The name of the interface
qDebug() << "Name: " << interface.name();
// Hardware address
qDebug() << "HardwareAddress: " << interface.hardwareAddress();
// You can get all through it ip Address
qDebug()<< "Ip address"<<interface.allAddresses();
// obtain IP List of address entries , Each entry contains a IP Address , A subnet mask and a broadcast address
QList<QNetworkAddressEntry> entryList = interface.addressEntries();//addressEntries() I can return one QNetworkAddressEntry List of objects
//QNetworkAddressEntry Class holds a network supported IP And it's time to IP Address related subnet mask and broadcast address
// Go through each one IP Address entry
foreach (QNetworkAddressEntry entry, entryList)
{
// IP Address
qDebug() << "IP Address: " << entry.ip().toString();
// Subnet mask
qDebug() << "Netmask: " << entry.netmask().toString();
// Broadcast address
qDebug() << "Broadcast: " << entry.broadcast().toString();
}
}
UDP Connect
This is the easiest way , Just send the packet , There is no need for him to reply , It doesn't matter whether the packet has been delivered or not , Is an unreliable connection
The sender :
QUdpSocket *sender;
sender = new QUdpSocket(this);
QByteArray datagram = "hello world!";
sender->writeDatagram(datagram.data(), datagram.size(),QHostAddress::Broadcast, 45454); // Broadcast address Port number
// The parameters are : data , Data length , The host address , The port number is address The host of port port
// The meaning is to send size The size of the packet data To the address
// Sending greater than... Is not recommended 512 Byte datagram ; The best port number is 1024 The above , The maximum is 65535 2 Of 16 Power
The receiver :
QUdpSocket *sender;
receiver = new QUdpSocket(this);
receiver->bind(45454, QUdpSocket::ShareAddress);// Consistent with the port number of the sending end There is no need to specify IP. All... Are supported by default IPV4, Binding mode indicates that other servers are allowed
// Whenever a datagram comes , Will trigger readyRead()
connect(receiver, SIGNAL(readyRead()), this, SLOT(processPendingDatagram()));
// Processing waiting datagrams
void Receiver::processPendingDatagram()
{
// Have a waiting datagram
while(receiver->hasPendingDatagrams()) //hasPendingDatagrams() Determine whether there are still waiting datagrams
{
QByteArray datagram;
// Give Way datagram The size of is the size of the datagram waiting to be processed , In order to receive the complete data
datagram.resize(receiver->pendingDatagramSize());//pendingDatagramSize() Current packet size
// Receiving datagrams , Store it in datagram in
receiver->readDatagram(datagram.data(), datagram.size());//readDatagram Save data no longer than the specified length to datagram.data()
ui->label->setText(datagram);
}
}
TCP Connect
TCP Connection is a reliable transport protocol for data flow and connection , Those who have learned Jiwang are familiar with this , If we use interface classes to write connections, we don't need to use them ourselves socket Three handshakes and four waves
Server side
Establishing a connection :
The server does not actively establish a connection , It is the port that monitors the connection , A full duplex connection will only be established with the connection request sent by the client
So let's create one QTcpServer object QTcpServer tcp_server;
Turn on TCP The server , Listen to all addresses , Port number :
( Which single port to listen to? Let's look at the parameter list of the function in detail )
tcp_server.listen(QHostAddress::Any,port);
When the client sends a connection request to the server , Slot function of signal processing sent :
connect(&tcpserver,SLGNAL(newConnection()),this,SLOT(answerConnection() Custom slot function ));
void answerConnection()
{
// Get socket to communicate with the client
QTcpServer* client_socket = tcp_server.nextPendingConnection();
// Save client socket
client_list.append(client_socket);
// When the client sends a message to the server , Trigger readyread The signal
connect(client_socket,SIGNAL,(readyread()),this,SLOT(answerReadyread()));
}
Receiving messages from clients :
void answerReadyread()
{
// Traverse to check which client has messages
for(int i = 0;i < client_list.size();i++)
{
// Get the number of bytes waiting for socket , No message returned 0
if(client_list.at[i]->bytesAvailable())
{
QByteArray buf = client_list.at(i)->readALL();// Read and save to buf
ui->listWidget->addItem(buf);// Display to the interface
sendMessage(buf);// Send to other clients
}
}
}
client
Establishing a connection :
QTcpSocket tcp_socket;// Create a socket to communicate with the server
tcp_socket.connectToHost(server_ip,server_port);// Send a connection request to the server
// When sending a connection to the server, it will send a signal connected
connect(&tcp_socket,SIGNAL(connected()),this,SLOT(answerConnected()));
// When the server forwards the message, it will send readyRead() The signal
connect(&tcp_socket,SIGNAL(readyRead()),this,SLOT(answerReadyRead()));
receive messages :
void answerReadyRead()
{
if(tcp_socket.bytesAvailable())// If there's news
{
QByteArray buf = tcp_socket.readAll();// Read out the message content
ui->listWidget->addItem(buf);// What to do depends on the business needs
}
}
边栏推荐
- 汇率的查询接口
- How to establish its own NFT market platform in 2022
- 高性能 低功耗Cortex-A53核心板 | i.MX8M Mini
- Gradle foundation | customize the plug-in and upload it to jitpack
- Verilog wire type
- [yolo3d]: real time detection of end-to-end 3D point cloud input
- 数据库文件逻辑结构形式指的是什么
- JS <2>
- Verilog 避免 Latch
- Retrofit's callback hell is really vulnerable in kotlin synergy mode
猜你喜欢
Comment élaborer une stratégie nuageuse à l'ère des nuages mixtes
Verilog 过程赋值 区别 详解
How to do medium and long-term stocks, and what are the medium and long-term stock trading skills?
MySQL advanced (Advanced) SQL statement (II)
一天上手Aurora 8B/10B IP核(5)----从Framing接口的官方例程学起
NLog使用
Gradle foundation | customize the plug-in and upload it to jitpack
[untitled] basic operation of raspberry pie (2)
初出茅庐市值1亿美金的监控产品Sentry体验与架构
Generate random numbers that obey normal distribution
随机推荐
Verilog wire type
Global and Chinese market of X-ray detectors 2022-2028: Research Report on technology, participants, trends, market size and share
What is the binding path of SAP ui5
Unity脚本的基础语法(7)-成员变量和实例化
Pointer array & array pointer
Oracle 查看被锁的表和解锁
C#联合halcon脱离halcon环境以及各种报错解决经历
Detailed explanation of ThreadLocal
Competition and adventure burr
Unity脚本的基础语法(6)-特定文件夹
Verilog 过程赋值 区别 详解
MySQL connection query and subquery
Sentry experience and architecture, a fledgling monitoring product with a market value of $100million
Verilog timing control
JS generate random numbers
Which of PMP and software has the highest gold content?
Intersection of Venn graph
Download and use of the super perfect screenshot tool snipaste
NLog使用
Global and Chinese markets for hand hygiene monitoring systems 2022-2028: Research Report on technology, participants, trends, market size and share