当前位置:网站首页>Qt-- realize TCP communication
Qt-- realize TCP communication
2022-06-12 06:20:00 【I have a mint】
Tips : This is the learning record , If there is an error , Please contact the author , Modest and educated .
List of articles
Preface
Life always comes and goes , Don't wait for a long time .
One 、TCP agreement
Transmission control protocol (TCP,Transmission Control Protocol) It's a connection oriented 、 reliable 、 Transport layer communication protocol based on byte stream .
advantage :
(1) Flow based approach ;
(2) Connection oriented ;
(3) Reliable means of communication ;
(4) When the network condition is not good, try to reduce the bandwidth cost caused by retransmission ;
(5) Communication connection maintenance is oriented to the two endpoints of communication , Without considering the intermediate network segment and node .
See in detail :《TCP website 》
To satisfy TCP These characteristics of the agreement ,TCP The agreement makes the following provisions :
① Data fragmentation : Segment the user data at the sending end , Regroup at the receiving end , from TCP Determine the size of the segments and control the fragmentation and recombination ;
② Arrival confirmation : When the receiving end receives the fragmentation data , Send a confirmation to the sender according to the slice data serial number ;
③ Timeout retransmission : The sender starts the timeout timer when sending the fragment , If you don't receive the corresponding confirmation after the timer timeout , Resend slice ;
④ The sliding window :TCP Each side of the connection has a fixed receive buffer size , The receiving end only allows the other end to send the data that the receiving end buffer can accept ,TCP Provide flow control on the basis of sliding windows , Prevent faster hosts from overflowing buffers on slower hosts ;
⑤ Out of order processing : As IP Datagram to transmit TCP Pieces may arrive out of order ,TCP The received data will be reordered , Deliver the received data to the application layer in the correct order ;
⑥ Reprocessing : As IP Datagram to transmit TCP The segments will repeat ,TCP The receiver of must discard the duplicate data ;
⑦ data verification :TCP Will keep its head and data checked and , This is an end-to-end inspection and , The purpose is to detect any changes in data during transmission . If you receive a patch check and there is an error ,TCP This fragment will be discarded , Failure to acknowledge receipt of this message segment causes the peer to time out and resend .
《 The legendary TCP Three handshakes of 》
The host computer acts as the client , Actively connect to the server , send data , receive data .
Simple understanding :
A send out : I want to send you a message , are you ready ?
B send out : I'm ready , You send it !
A send out : well , I'll send it .
then A Start sending .
This is the three handshakes on the understanding level .
The following will be relevant QT Simple example of .
Two 、TCP Communication steps
1.TCP The implementation process of the server
a key :
A. call listen Listening port
B. Connecting signals newConnection, Call in slot function nextPendingConnection Get connected socket.
(1).h Import header file
#include <QTcpServer>
#include <QTcpSocket>
(2) establish QTcpServer Object used as a listening socket ;
QTcpServer *m_s;
QTcpSocket *m_tcp;
In the constructor new
// Put in constructor
m_s = new QTcpServer(this);
(3) Use listen() Method to monitor the network card ip And port
void MainWindow::on_bt_listen_clicked()
{
unsigned short port = ui->lineEdit->text().toUShort();
bool ret =m_s->listen(QHostAddress::Any, port);
if(ret)
{
ui->textEdit->append(" Start the server successfully ");
}
else {
ui->textEdit->append("error");
}
qDebug()<<ret<<m_s->errorString();
}
(4) Send a message
void MainWindow::on_bt_sendmsg_clicked()
{
QString msg = ui->text_send->toPlainText();
m_tcp->write(msg.toUtf8());
ui->textEdit->append(" The server said :"+msg);
}
(5) Close the connection
void MainWindow::on_bt_close_clicked()
{
// Actively disconnect from the client
if(NULL == m_tcp)
{
return;
}
m_tcp->disconnectFromHost();
m_tcp->close();
m_tcp = NULL;
}
(6) Trigger the slot function above , Use... In the constructor connect()
When there is data transmission , client QTcpSocket Will trigger readyRead() The signal , then readAll() Read the data and display it .
connect(m_s,&QTcpServer::newConnection,this,[=]()
{
m_tcp = m_s->nextPendingConnection();
ui->textEdit->append(" Successfully established a connection with the client !");
connect(m_tcp,&QTcpSocket::readyRead,this,[=]()
{
QByteArray data = m_tcp->readAll();
ui->textEdit->append(" Client said :"+data);
});
connect(m_tcp,&QTcpSocket::disconnected,this,[=]()
{
ui->textEdit->append(" Client disconnected !");
m_tcp->close();
m_tcp->deleteLater();
});
});
2.TCP The implementation process of the client
a key :
A. call connectToHost Connect to server
B. call waitForConnected Determine if the connection is successful
C. Connecting signals readyRead Slot function , Reading data asynchronously
D. call waitForReadyRead, Blocking read data
E. call disconnected disconnect
F. call state() == QAbstractSocket::UnconnectedState and waitForDisconnected Determine whether to disconnect
(1).h Import header file
#include <QTcpSocket>
(2) establish QTcpSocket Socket
QTcpSocket *tcpsocket;// Communication socket
In the constructor new
tcpsocket = new QTcpSocket(this);
(3) Use this object to connect to the server
void MainWindow::on_bt_lianjie_clicked()
{
qint16 port = ui->tcp_com->text().toInt();
//unsigned short ip = ui->ip->text().toUShort();
QString ip = ui->tcp_add->text();
tcpsocket->connectToHost(QHostAddress(ip),port);
if(tcpsocket->waitForConnected(3000))
{
ui->textdisplay->append(" Successfully connected to the server !");
}
else
{
ui->textdisplay->append(" The connection fails , Please check IP Address and port !");
}
}
(4) Send a message write()
void MainWindow::on_pushButton_clicked()
{
QString msg = ui->text_send->toPlainText();
ui->textdisplay->append(" Client said :"+msg);
// Get the contents of the edit box
QString str = ui->text_send->toPlainText();
// send data
tcpsocket->write(str.toUtf8().data());
ui->textdisplay->append(" The client sends :"+str);
}
(5) disconnect
void MainWindow::on_bt_duankai_clicked()
{
// Take the initiative to disconnect from the other party
tcpsocket->disconnectFromHost();
tcpsocket->close();
// Disconnection succeeded
if (tcpsocket->state() == QAbstractSocket::UnconnectedState || tcpsocket->waitForDisconnected(1000))
{
ui->textdisplay->append(" connection dropped !");
}
else
{
ui->textdisplay->append(" Unable to disconnect from server !");
}
}
(6) Trigger the slot function above , Use... In the constructor connect()
When the client's nested word socket When new data arrives in the receive buffer , Will be issued readRead() The signal
connect(tcpsocket,&QTcpSocket::connected,this,[=]()
{
ui->textdisplay->append(" Successfully established a connection with the server !");
});
connect(tcpsocket,&QTcpSocket::readyRead,this,[=]()
{
QByteArray data = tcpsocket->readAll();
ui->textdisplay->append(" The server said :"+data);
});
connect(tcpsocket,&QTcpSocket::disconnected,this,[=]()
{
//m_tcp->close();
//m_tcp->deleteLater();
ui->textdisplay->append(" Disconnected from server !");
});

summary
Tips : Good at summarizing , More further .
边栏推荐
- dlib 人脸检测
- Dlib face detection
- Cross compile libev
- Textcnn (MR dataset - emotion classification)
- Excel VBA opens a file that begins with the specified character
- N-degree Bessel curve
- zip 和.items()区别
- The first principle of thinking method
- Project and build Publishing
- Unity C script implements AES encryption and decryption
猜你喜欢

Houdini terrain creation

SQLite cross compile dynamic library

Houdini script vex learning

BRDF of directx11 advanced tutorial PBR (2)

LeetCode个人题解(剑指offer3-5)3.数组中重复的数字,4.二维数组中的查找,5.替换空格

Computer composition and design work06 —— 基于MIPS

Why is the union index the leftmost matching principle?

dlib 人脸检测

Book classification based on Naive Bayes

C2w model - language model
随机推荐
Textcnn (MR dataset - emotion classification)
Word2Vec
Unity3d multi platform method for reading text files in streamingasset directory
Why is the union index the leftmost matching principle?
Computer composition and design work05 ——fifth verson
SQL注入原理即sqli-labs搭建,sql注入简单实战
dlib 人脸检测
Project and build Publishing
Redis队列
Unreal Engine learning notes
Unity3d script captures a sub area from the screen and saves it as texture2d, which is used to save pictures and maps
RMB classification II
姿态估计之2D人体姿态估计 - PifPaf:Composite Fields for Human Pose Estimation
JS变量作用域
线程有哪些状态?
Modifying theme styles in typora
获取图片的尺寸
Highlight detection with pairwise deep ranking for first person video summary (thesis translation)
IBL of directx11 advanced tutorial PBR (3)
Sensor bringup 中的一些问题总结