当前位置:网站首页>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 .
边栏推荐
- Information content security experiment of Harbin Institute of Technology
- Leetcode-717. 1-bit and 2-bit characters (O (1) solution)
- Leetcode-1512. Number of good pairs
- 勤于奋寻找联盟程序方法介绍
- Univariate linear regression model
- Redis queue
- Leetcode-1552. Magnetic force between two balls
- Cross compile libev
- C2w model - language model
- AI作业ch8
猜你喜欢

n次贝塞尔曲线

Unity implements smooth interpolation

Chartextcnn (Ag dataset - news topic classification)

为什么数据库不使用二叉树、红黑树、B树、Hash表? 而是使用了B+树

The vs 2019 community version Microsoft account cannot be logged in and activated offline

Computer composition and design work06 —— 基于MIPS

IDEA常用配置

Findasync and include LINQ statements - findasync and include LINQ statements

Understand Houdini's (heightfield) remap operation

Leetcode-1043. Separate arrays for maximum sum
随机推荐
JS预解析
cv2.fillPoly coco annotator segment坐标转化为mask图像
Cross compile libev
Dlib face detection
Unity custom translucent surface material shader
为什么数据库不使用二叉树、红黑树、B树、Hash表? 而是使用了B+树
Modifying theme styles in typora
(UE4 4.27) add globalshder to the plug-in
About why GPU early-z reduces overdraw
. Net core and Net framework comparison
Poisson disk sampling for procedural placement
Nodemon cannot load the file c:\users\administrator\appdata\roaming\npm\nodemon PS1, because script execution is prohibited in this system
Univariate linear regression model
JS pre parsing
R语言大作业(四):上海市、东京 1997-2018 年GDP值分析
The vs 2019 community version Microsoft account cannot be logged in and activated offline
(UE4 4.27) customize globalshader
Leetcode-1535. Find the winner of the array game
Excel VBA opens a file that begins with the specified character
Houdini & UE4 programmed generation of mountains and multi vegetation scattering points