Qt 多线程TCP服务端一键关闭所有客户端
Qt 多線程TCP服務端一鍵關閉所有客戶端
任務描述: 實現多線程TCP服務端一鍵關閉所有客戶端的連接。
解決過程: 1、Qt的服務端提供了close的功能,但是只用來不響應新接入的客戶端。
手冊中是這樣描述的:
void QTcpServer::close()
Closes the server. The server will no longer listen for incoming connections.
2、既然是多線程的服務端,每個客戶端對應一個線程,那么將所有的線程都退出或者終止不就可以實現關閉所有的客戶端了。
代碼實現過程:
1、創建 threadList 成員用來管理線程
2、修改incomingConnection()函數如下,對每一個客戶端創建一個線程,同時將線程的指針地址添加threadlist中.
void MyTcpServer::incomingConnection(int sockDesc) {threadCount++;m_socketList.append(sockDesc);thread = new serverThread(sockDesc);threadlist.append(thread);//顯示連接數connect(thread, SIGNAL(connectTCP(int,QString )), m_Widget, SLOT(showConCont(int,QString)));//顯示客戶端IPconnect(thread, SIGNAL(connectTCP(int,QString )), m_Widget, SLOT(showConnection(int,QString)));connect(thread, SIGNAL(disconnectTCP(int,QString)), m_Widget, SLOT(showDisconnection(int,QString)));connect(thread, SIGNAL(disconnectTCP(int,QString)), this, SLOT(disconnect(int,QString)));connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));//接收數據connect(thread, SIGNAL(dataReady(const QString&, const QByteArray&)),m_Widget, SLOT(recvData(const QString&, const QByteArray&)));//發送數據dconnect(m_Widget, SIGNAL(sendData(int,QString, const QByteArray&)),thread, SLOT(sendDataSlot(int,QString, const QByteArray&)));thread->start();}2、實現信號槽函數,實現關閉所有線程。在調試的過程中發現,如果delete thread[i],可能會導致程序出錯。
注意到 connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); 當線程終止的時候,自動會清理內存,所以不需要手動清理。為了避免列表對象只增不減,所以每當服務端關閉的時候,同時也清理線程列表。
3、主窗口點擊斷開鏈接后,發送斷開所有連接的信號,所以需要將此信號與信號槽disconnectAll()關聯。
connect(this, SIGNAL(disconnectAllClients()), m_server, SLOT(disconnectAll()));4、最后完善主界面的uI的顯示部分
severDisc = true;emit disconnectAllClients();ui->comboBox_ClientIP->clear(); ui->pushButton_Listen->setText("偵聽");ui->statusbar->showMessage("服務端關閉所有的連接!"); m_server->close(); //服務器將不再監聽新接入的客戶端這樣就完成了。
總結
以上是生活随笔為你收集整理的Qt 多线程TCP服务端一键关闭所有客户端的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qt多线程 TCP 服务端
- 下一篇: Qt 并行计算 Concurrent R