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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

Qt下TCP编程

發布時間:2023/12/18 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Qt下TCP编程 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、服務器

1、聲明一個QTcpServer對象

QTcpServer* serverListener;

2、new出對象

this->serverListener = new QTcpServer();

3、服務器監聽

QHostAddress ipAddress(“192.168.1.1”);

quint16 ipPort = 8080;

serverListener->listen(ipAddress,ipPort);

4、聲明一個QList對象用于存客戶端

QList<QTcpSocket*> clientList;

5、連接信號與槽

QObject::connect(this->serverListener,SIGNAL(newConnection()),this,SLOT(newConnection()));//newConnection是自定義槽函數,用于管理clientList列表

6、實現newConnection函數,保存客戶端至clientList

void TcpServer::newConnection()

{

  QTcpSocket* serverClient = this->serverListener->nextPendingConnection();//new出客戶端對象

  this->clientList.append(serverClient);//保存

  QObject::connect(serverClient,SIGNAL(readyRead()),this,SLOT(rcvData()));//當此客戶端有數據時在自定義rcvData函數里接收

  QObject::connect(serverClient,SIGNAL(disconnected()),this,SLOT(removeClient()));//當此客戶端斷開連接時,會發出disconnected信號,在自定義removeClient里去除客戶端

}

7、實現removeClient函數,去除客戶端

void TcpServer::removeClient()

{

  for(int i=0;i<this->clientList.length();i++)

  {

  if(clientList.at(i)->socketDescriptor() == -1)//用于判斷當前客戶端是否有效

    clientList.removeAt(i);

  }

}

8、實現rcvData函數,接收數據

void TcpServer::rcvData()

{ 

  QByteArray ba;
  for(int i=0;i<this->clientList.length();i++)
  {
    if(clientList.at(i)->atEnd() == true)
      continue;
    ba = clientList.at(i)->readAll();

    //
  }

}

9、發送數據

clientList.at(n)->write(QByteArray ba);

10、停止

serverListener->close();

二、客戶端

1、聲明一個QTcpSocket對象

QTcpSocket* tcpClient;

2、new出對象

this->tcpClient = new QTcpSocket();

3、連接服務器,連接信號與槽

tcpClient->connectToHost("192.168.1.1","8080");

QObject::connect(this->tcpClient,SIGNAL(readyRead()),this,SLOT(rcvData()));//rcvData是自定義接收槽函數

4、實現rcvData函數,接收數據

void TcpClient::rcvData()

{

  QByteArray ba = tcpClient->readAll();

}

5、發送數據

tcpClient->write(QByteArray ba);

6、關閉

tcpClient->close();

ps:軟件開發流程

?

總結

以上是生活随笔為你收集整理的Qt下TCP编程的全部內容,希望文章能夠幫你解決所遇到的問題。

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