当前位置:网站首页>QT multithreaded TCP server
QT multithreaded TCP server
2022-06-13 08:59:00 【one-rabbit】
1、 Function realization

2、 Simplified procedure
Use one Map<String,int> To store the client's socket Of ip And client index ( from 0 Start ).
Around this creation process .
1、 The key point is how to handle the new Socket Connect
2、 understand socket Key signals and processes of communication 
3、 Simple analysis of part of the code
Important code 1: Deal with new arrivals socket
void CServerPool::dealNewSocket(qintptr socketDes)
{
// Deal with new arrivals soketDes
m_numT++;
if(m_numT<=m_maxT){
// Handle Not exceeded
int index=0;
if(!m_mapVec.isEmpty()){
index=m_mapVec.begin().key();
m_mapVec.remove(index);
}
else{
index=m_numT-1;
}
if (!m_threadVec.at(index).m_thread->isRunning()) {
m_threadVec.at(index).m_thread->start();
delayMs(600);// Delay 600ms Wait for the thread to start
}
emit m_threadVec.at(index).m_myT->newSocket(index,socketDes);// Send to new socket
}
else{
m_numT=m_maxT;// Avoid back and forth index error
int index = 0;
if (!m_mapQue.isEmpty()) {
index = m_mapQue.begin().key();
m_mapQue.remove(index);
}
else {
index = m_numQue;
++m_numQue;
}
if (!m_threadQ->isRunning()){
m_threadQ->start();
delayMs(600);// Delay 600ms
}
emit m_queueT->newSocket(index,socketDes);
}
}
Important code 2: Thread group Of socket The creation of
void MyThread::dealNewSocket(int index,qintptr socketDes)
{
qDebug()<<" Current thread id"<<QThread::currentThreadId();
if (!m_socket) {
m_socket = new MySocket;
if (!m_socket->t0) {
m_socket->t0 = new QTimer;
connect(m_socket->t0, &QTimer::timeout, [=]() {
double nowTime = QDateTime::currentDateTime().toSecsSinceEpoch();
if (nowTime - m_socket->m_frontTime > m_socket->m_outTime) {
QString str = QString("%1 %2 It's over time ").arg(
m_socket->peerAddress().toString().mid(7)).arg(index);
m_socket->t0->stop();
if (m_socket->isOpen())
m_socket->close();
delayMs(1000);
emit timeOut(m_socket->index, str);
}
});
}
// Read
connect(m_socket, &MySocket::readyRead, [=]() {
m_socket->t0->stop();
QByteArray data = m_socket->readAll();
QString str = m_socket->peerAddress().toString().mid(7);
QString ip=str+QString(" %1").arg(m_socket->index);
emit sendData(ip, data);
m_socket->m_frontTime = QDateTime::currentDateTime().toSecsSinceEpoch();
m_socket->t0->start(1000);
});
// disconnect
connect(m_socket, &QTcpSocket::disconnected, [=]() {
QString str = QString("%1 %2 The connection has been disconnected ").arg(
m_socket->peerAddress().toString().mid(7)).arg(index);
QString ip = m_socket->peerAddress().toString();
emit socketDisConnected(m_socket->index, ip, str);
m_socket->t0->stop();
if(m_socket->isOpen())
m_socket->close();
});
}
m_socket->index = index;
if(m_socket->isOpen())
m_socket->close();
m_socket->setSocketDescriptor(socketDes);// Set up socket The logo of
QString ip=m_socket->peerAddress().toString();
emit sendAddress(index,ip);
m_socket->m_frontTime = QDateTime::currentDateTime().toSecsSinceEpoch();
m_socket->t0->start(1000);// For the first time, it needs to start automatically
}
Important code 3: Queue thread pair socket The creation of
void QueueThread::dealNewSocket(int index, qintptr socketDes)
{
MySocket *m_socket = new MySocket;
m_socket->t0 = new QTimer;
m_socket->setSocketDescriptor(socketDes);
m_socket->index = index;
QString ip=m_socket->peerAddress().toString().mid(7)+QString(" %1").arg(index);
m_mapDsocket.insert(ip,m_socket);// Add to the specified list
// Read
connect(m_socket->t0, &QTimer::timeout, [=]() {
double nowTime = QDateTime::currentDateTime().toSecsSinceEpoch();
if (nowTime - m_socket->m_frontTime > m_socket->m_outTime) {
int lsIndex = m_socket->index;
QString str = QString("%1 %2 It's over time ").arg(
m_socket->peerAddress().toString().mid(7)).arg(lsIndex);
m_socket->t0->stop();
if (m_socket->isOpen())
m_socket->close();
delayMs(1000);
emit timeOut(str);
}
});
connect(m_socket, &MySocket::readyRead, [=]() {
m_socket->t0->stop();
QByteArray data = m_socket->readAll();
QString ip = m_socket->peerAddress().toString().mid(7)+
QString(" %1").arg(m_socket->index);
emit sendData(ip, data);
m_socket->m_frontTime = QDateTime::currentDateTime().toSecsSinceEpoch();
m_socket->t0->start(1000);
});
// disconnect
connect(m_socket, &QTcpSocket::disconnected, [=]() {
int lsIndex = m_socket->index;
QString ip = m_socket->peerAddress().toString().mid(7)+QString(" %1").arg(lsIndex);
QString str = QString("%1 The connection has been disconnected ").arg(ip);
emit socketDisConnected(lsIndex, ip, str);
m_socket->t0->stop();// off timer
if (m_socket->isOpen()) {
m_socket->close();
delete m_socket;
}
m_mapDsocket.remove(ip);
});
emit sendAddress(index,ip);// Return the successful address
m_socket->t0->start(1000);
m_socket->m_frontTime = QDateTime::currentDateTime().toSecsSinceEpoch();
}
No time to upload github and git; I'll make it up later Corresponding links
Resources to address :https://download.csdn.net/download/a1ngel/82470844
边栏推荐
- 20211028 Stabilizability
- Knowledge points related to system architecture 1
- JS string method
- Mapbox loads nationwide and provincial range, displaying multi-color animation points, migration lines, 3D histogram, etc
- Jfinal and swagger integration
- Number of parameters of pytorch statistical model
- VBA format word (page, paragraph, table, picture)
- 关于RSA加密解密原理
- Uni app subcontracting loading and optimization
- Brief description of port, domain communication port and domain service
猜你喜欢

A solution to create a new EXCEL workbook on win10 computer and change the suffix to xlsm (normally it should be xlsx)

About RSA encryption and decryption principle

Cesium achieves sunny, rainy, foggy, snowy and other effects

Invalid flex layout setting width

Cesium displays a pop-up box at the specified position and moves with the map

【安全】零基础如何从0到1逆袭成为安全工程师

transforms. ColorJitter(0.3, 0, 0, 0)

Top+jstack to analyze the causes of excessive CPU

Jfinal and swagger integration

Diversified tables through TL table row consolidation
随机推荐
如何成为白帽子黑客?我建议你从这几个阶段开始学习
Software Architecture Overview knowledge
Is it safe to open an account online? Can a novice open an account?
GBase 常见网络问题及排查方法
À propos des principes de chiffrement et de décryptage RSA
System analysis - detailed description
Web page H5 wechat sharing
Completely uninstall PostgreSQL under Linux
ES6 use of dynamic attributes
Screenshot of cesium implementation scenario
Mapbox usage, including drawing, loading, modifying, deleting points and faces, displaying pop ups, etc
1. Learning sequence of SolidWorks modules
20211108 微分跟踪器
1. preliminary understanding of Express
20211005 Hermite矩阵及几个性质
20220524 如何把CoppeliaSim安装到D盘
Cesium view switching, locating, reading files, building data sources, entity control, model control, etc
How to save the video of wechat video number locally?
pytorch相同结构不同参数名模型加载权重
Can I open an account for the reverse repurchase of treasury bonds? Can I directly open the security of securities companies on the app for the reverse repurchase of treasury bonds? How can I open an