当前位置:网站首页>QT multithreaded TCP server

QT multithreaded TCP server

2022-06-13 08:59:00 one-rabbit

1、 Function realization

 Insert picture description here

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
 Insert picture description here

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

原网站

版权声明
本文为[one-rabbit]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202270535463331.html