QT編寫tcp通信工具(Server端)
本文實例為大家分享了QT編寫Server端的tcp通信工具的具體代碼,供大家參考,具體內(nèi)容如下
1.說明
使用qt寫一個類似網(wǎng)上常見的網(wǎng)絡(luò)調(diào)試工具。此篇為Server端。Client端在上一篇。
2.基本流程
新建QTcpServer對象,為其newConnection信號寫槽函數(shù)。此為新的Client連接信號,在其對應(yīng)槽函數(shù)里使用nextPendingConnection方法獲取Client對象,并為Client添加readyRead(讀數(shù)據(jù)),disconnected(斷開連接)兩個信號寫槽函數(shù)。
開始監(jiān)聽使用Server的listen方法,停止監(jiān)聽使用Server的close方法。
主動斷開某個連接可使用Client對象的disconnectFromHost方法。需要注意的是,這會觸發(fā)disconnected信號。應(yīng)小心處理,避免重復(fù)刪除鏈表,導(dǎo)致程序崩潰。
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())); ? ? } } ? //接收數(shù)據(jù) 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); ? ? } } ? //打開監(jiān)聽與停止 void MainWindow::on_btnOpen_clicked() { ? ? if(ui->btnOpen->text() == "停止")//主動停止監(jiān)聽 ? ? { ? ? ? ? ? if( !tcpClients.isEmpty() ) ? ? ? ? for(int i=0; i<tcpClients.length(); i++)//斷開所有連接 ? ? ? ? { ? ? ? ? ? ? tcpClients[i]->disconnectFromHost(); //會觸發(fā)disconnected信號 ? ? ? ? } ? ? ? ? tcpClients.clear(); ? ? ? ? tcpServer->close(); ? ? ? ? ui->lwdgClientsIp->clear(); ? ? ? ? ui->btnOpen->setText("監(jiān)聽"); ? ? ? ? ui->btnSend->setEnabled(false); ? ? }else{ //打開監(jiān)聽 ? ? ? ? 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); ? ? ? ? } ? ? } } ? //發(fā)送數(shù)據(jù),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()); ? ? } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Opencv實現(xiàn)讀取攝像頭和視頻數(shù)據(jù)
這篇文章主要為大家詳細介紹了Opencv實現(xiàn)讀取攝像頭和視頻數(shù)據(jù),具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-01-01Linux網(wǎng)絡(luò)編程之socket文件傳輸示例
這篇文章主要介紹了Linux網(wǎng)絡(luò)編程之socket文件傳輸示例,對于基于Linux平臺的C程序員來說有一定的借鑒價值,需要的朋友可以參考下2014-08-08詳解C++值多態(tài)中的傳統(tǒng)多態(tài)與類型擦除
值多態(tài)是一種介于傳統(tǒng)多態(tài)與類型擦除之間的多態(tài)實現(xiàn)方式,借鑒了值語義,保留了繼承,在單繼承的適用范圍內(nèi),程序和程序員都能從中受益。這篇文章主要介紹了C++值多態(tài)中的傳統(tǒng)多態(tài)與類型擦除,需要的朋友可以參考下2020-04-04C++Node類Cartographer開始軌跡的處理深度詳解
這篇文章主要介紹了C++Node類Cartographer開始軌跡的處理,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-03-03