網站首頁 編程語言 正文
本文實例為大家分享了QT編寫Server端的tcp通信工具的具體代碼,供大家參考,具體內容如下
1.說明
使用qt寫一個類似網上常見的網絡調試工具。此篇為Server端。Client端在上一篇。
2.基本流程
新建QTcpServer對象,為其newConnection信號寫槽函數。此為新的Client連接信號,在其對應槽函數里使用nextPendingConnection方法獲取Client對象,并為Client添加readyRead(讀數據),disconnected(斷開連接)兩個信號寫槽函數。
開始監聽使用Server的listen方法,停止監聽使用Server的close方法。
主動斷開某個連接可使用Client對象的disconnectFromHost方法。需要注意的是,這會觸發disconnected信號。應小心處理,避免重復刪除鏈表,導致程序崩潰。
3.代碼
這是mainwindow.cpp文件
#include "mainwindow.h"
#include <QApplication>
?
MainWindow::MainWindow(QWidget *parent) :
? ? QMainWindow(parent),
? ? ui(new Ui::MainWindow)
{
? ? ui->setupUi(this);
? ? ui->splitter->setStretchFactor(0,2);
? ? ui->splitter->setStretchFactor(1,1);
? ? tcpServer = new QTcpServer(this);
? ? //qWarning()<<QNetworkInterface().allAddresses();
? ? QString ip=getLocalip();
? ? if( ip.isEmpty() )
? ? {
? ? ? ? QMessageBox::about(this,tr("提示"),tr("無本地IP。") ) ;
? ? }
? ? else{
?
? ? ? ? ui->ledtIp->setText( ip ); ? //本地IP
? ? }
? ? ui->labHostName->setText(tr("HostName:")+ QHostInfo::localHostName() );
? ? ui->labHostName->adjustSize();
? ? ui->ledtPort->setText(tr("8080"));
? ? ui->btnOpen->setEnabled(true);
? ? ui->btnSend->setEnabled(false);
? ? iplistMenu = new ?QMenu( ?ui->lwdgClientsIp );
? ? iplistMenu->addAction(ui->actiondel);
? ? connect( ui->actiondel, SIGNAL(triggered()), this, SLOT(slot_delmenu()));
? ? connect(tcpServer, SIGNAL(newConnection()), this, SLOT(slot_newConnectionClient()));
}
?
MainWindow::~MainWindow()
{
? ? delete ui;
}
//獲取本地IP
/*
QString MainWindow::getLocalip()
{
? ? QHostInfo info = QHostInfo::fromName( QHostInfo::localHostName() );
? ? foreach(QHostAddress addr,info.addresses())
? ? {
? ? ? ? if(addr.protocol()==QAbstractSocket::IPv4Protocol)
? ? ? ? {
? ? ? ? ? ? return ?addr.toString();
? ? ? ? }
? ? }
? ? return "";
}
*/
QString MainWindow::getLocalip()
{
? ? QList<QHostAddress> list = QNetworkInterface::allAddresses();
? ? foreach (QHostAddress address, list)
? ? {
? ? ? ? if( address.protocol() == QAbstractSocket::IPv4Protocol)
? ? ? ? {
? ? ? ? ? ? return address.toString();
? ? ? ? }
? ? }
? ? ? ? return "";
}
?
//處理來自新的client連接
void MainWindow::slot_newConnectionClient()
{
? ? while (tcpServer->hasPendingConnections())
? ? {
? ? ? ? QTcpSocket *client = tcpServer->nextPendingConnection();
? ? ? ? tcpClients.append(client);
?
? ? ? ? ui->lwdgClientsIp->addItem( tr("%1:%2").arg(client->peerAddress().toString()).arg(client->peerPort()) );
? ? ? ? connect(client, SIGNAL(readyRead()), this, SLOT(slot_readData()));
? ? ? ? connect(client, SIGNAL(disconnected()), this, SLOT(slot_disconnectedClient()));
? ? }
}
?
//接收數據
void MainWindow::slot_readData()
{
? ? QTcpSocket *obj = (QTcpSocket*)sender();
? ? QByteArray buf = obj->readAll();
? ? if(buf.isEmpty()) ? ?return;
?
? ? QString ipc;
? ? ipc = tr("[%1:%2]>").arg(obj->peerAddress().toString()).arg(obj->peerPort());
? ? ui->teRecive->appendPlainText(ipc);
? ? ui->teRecive->appendPlainText(buf);
}
?
//斷開連接處理
void ?MainWindow::slot_disconnectedClient()
{
? ? if( !tcpClients.isEmpty() ){
? ? ? ? QTcpSocket *obj = (QTcpSocket*)sender();
? ? ? ? QListWidgetItem *item = ?ui->lwdgClientsIp->findItems(
? ? ? ? ? ? tr("%1:%2")\
? ? ? ? ? ? .arg( obj->peerAddress().toString())\
? ? ? ? ? ? .arg( obj->peerPort()),Qt::MatchContains|Qt::MatchEndsWith
? ? ? ? ? ? ).at(0);
?
? ? ? ? ui->lwdgClientsIp->removeItemWidget( item );
? ? ? ? delete item;
? ? ? ? obj->close();
? ? ? ? tcpClients.removeOne(obj);
? ? }
}
?
//打開監聽與停止
void MainWindow::on_btnOpen_clicked()
{
? ? if(ui->btnOpen->text() == "停止")//主動停止監聽
? ? {
?
? ? ? ? if( !tcpClients.isEmpty() )
? ? ? ? for(int i=0; i<tcpClients.length(); i++)//斷開所有連接
? ? ? ? {
? ? ? ? ? ? tcpClients[i]->disconnectFromHost(); //會觸發disconnected信號
? ? ? ? }
? ? ? ? tcpClients.clear();
? ? ? ? tcpServer->close();
? ? ? ? ui->lwdgClientsIp->clear();
? ? ? ? ui->btnOpen->setText("監聽");
? ? ? ? ui->btnSend->setEnabled(false);
? ? }else{ //打開監聽
? ? ? ? if( ?ui->ledtPort->text().toInt() == 0 )
? ? ? ? {
? ? ? ? ? ? QMessageBox::about(this,tr("提示"),tr("請輸入端口號。") ) ;
? ? ? ? }
? ? ? ? else
? ? ? ? if( tcpServer->listen( QHostAddress::AnyIPv4 ?, ui->ledtPort->text().toInt() ) )
? ? ? ? {
? ? ? ? ? ? ui->btnOpen->setText("停止");
? ? ? ? ? ? ui->btnSend->setEnabled(true);
? ? ? ? }
? ? }
}
?
//發送數據,UTF8模式
void MainWindow::on_btnSend_clicked()
{
? ? if( ui->lwdgClientsIp->selectedItems().length() >0 ){
? ? ? ? foreach( QListWidgetItem* item ,ui->lwdgClientsIp->selectedItems() )
? ? ? ? {
? ? ? ? ? ? QString clientIP = item->text().split(":")[0];
? ? ? ? ? ? int clientPort = item->text().split(":")[1].toInt();
? ? ? ? ? ? for(int i=0; i<tcpClients.length(); i++)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? if(tcpClients[i]->peerAddress().toString()==clientIP && tcpClients[i]->peerPort()==clientPort)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? tcpClients[i]->write(ui->teSend->toPlainText().toUtf8() );
? ? ? ? ? ? ? ? ? ? break;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }
? ? }
}
//“刪除”菜單,停止某個Client
void MainWindow:: slot_delmenu()
{
? ? if( ?lwdgitem != NULL )
? ? {
? ? ? ? if( !tcpClients.isEmpty() ){
? ? ? ? ? ? QString clientIP = lwdgitem->text().split(":")[0];
? ? ? ? ? ? int clientPort = lwdgitem->text().split(":")[1].toInt();
? ? ? ? ? ? for(int i=0; i<tcpClients.length(); i++)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? if(tcpClients[i]->peerAddress().toString()==clientIP && tcpClients[i]->peerPort()==clientPort)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? tcpClients[i]->disconnectFromHost();
? ? ? ? ? ? ? ? ? ? break;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }
? ? }
}
//彈出菜單
void MainWindow::on_lwdgClientsIp_customContextMenuRequested(const QPoint &pos)
{
? ? lwdgitem=ui->lwdgClientsIp->itemAt(pos ) ;//判斷是否在項目上
? ? if( ?lwdgitem != NULL )
? ? {
? ? ? ? iplistMenu->exec(QCursor::pos());
? ? }
}
原文鏈接:https://blog.csdn.net/wangzibigan/article/details/121410083
相關推薦
- 2023-07-02 oracle數據庫排序后如何獲取第一條數據_oracle
- 2022-04-03 基于Docker實現Redis主從+哨兵搭建的示例實踐_docker
- 2022-08-20 PostgreSQL實現按年、月、日、周、時、分、秒的分組統計_PostgreSQL
- 2022-03-30 C語言入門之淺談數據類型和變量常量_C 語言
- 2023-07-26 webpack優化代碼運行之Code split
- 2021-12-05 解析Redis?數據結構之簡單動態字符串sds_Redis
- 2022-10-11 主從同步中斷(sql_thread)問題一例
- 2022-11-11 Python?第三方庫?Pandas?數據分析教程_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支