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客户端通信(本地回环)
- 下一篇: OpenCore 的代码结构