日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Qt 多线程TCP服务端一键关闭所有客户端

發布時間:2025/3/15 编程问答 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 成員用來管理線程

QList<serverThread *>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())); 當線程終止的時候,自動會清理內存,所以不需要手動清理。為了避免列表對象只增不減,所以每當服務端關閉的時候,同時也清理線程列表。

void MyTcpServer:: disconnectAll() {for(int i = 0;i<threadlist.length();i++){if(threadlist[i]->isRunning()){threadlist[i]->quit();threadlist[i]->wait();qDebug()<<i;//delete threadlist[i]; //清理對象}else{qDebug()<<"thread i is not runnint!";}}threadlist.clear(); //清理線程列表 }

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服务端一键关闭所有客户端的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。