当前位置:网站首页>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
}
}
边栏推荐
- 微信小程序中 在xwml 中使用外部引入的 js进行判断计算
- MySQL之账号管理
- One of the future trends of SAP ui5: embrace typescript
- Verilog 过程赋值 区别 详解
- Global and Chinese markets for ultrasonic probe disinfection systems 2022-2028: Research Report on technology, participants, trends, market size and share
- Gradle foundation | customize the plug-in and upload it to jitpack
- Unity脚本的基础语法(7)-成员变量和实例化
- C#联合halcon脱离halcon环境以及各种报错解决经历
- KL divergence is a valuable article
- Review materials of project management PMP high frequency examination sites (8-1)
猜你喜欢

JS <2>

Verilog state machine

Which of PMP and software has the highest gold content?

Detailed explanation of ThreadLocal
![[HCIA continuous update] working principle of OSPF Protocol](/img/bc/4eeb091c511fd563fb1e00c8c8881a.jpg)
[HCIA continuous update] working principle of OSPF Protocol

Download and use of the super perfect screenshot tool snipaste

Docker安装canal、mysql进行简单测试与实现redis和mysql缓存一致性

Framing in data transmission
![[yolo3d]: real time detection of end-to-end 3D point cloud input](/img/5e/f17960d302f663db75ad82ae0fd70f.jpg)
[yolo3d]: real time detection of end-to-end 3D point cloud input

SAML2.0 笔记(一)
随机推荐
Spark Tuning
微信小程序中 在xwml 中使用外部引入的 js进行判断计算
Uniapp uses canvas to generate posters and save them locally
Unity脚本的基础语法(6)-特定文件夹
js生成随机数
《MATLAB 神经网络43个案例分析》:第41章 定制神经网络的实现——神经网络的个性化建模与仿真
命名块 verilog
【DesignMode】原型模式(prototype pattern)
Pointer array & array pointer
PHP array processing
Global and Chinese market of handheld ultrasonic scanners 2022-2028: Research Report on technology, participants, trends, market size and share
Yan Rong looks at how to formulate a multi cloud strategy in the era of hybrid cloud
Intersection vengraph
Calculation of page table size of level 2, level 3 and level 4 in protection mode (4k=4*2^10)
venn圖取交集
32, 64, 128 bit system
高性能 低功耗Cortex-A53核心板 | i.MX8M Mini
Kotlin基础学习 17
Global and Chinese markets for electronic laryngoscope systems 2022-2028: Research Report on technology, participants, trends, market size and share
PY3 link MySQL