Qt下TCP编程
一、服務(wù)器
1、聲明一個(gè)QTcpServer對(duì)象
QTcpServer* serverListener;
2、new出對(duì)象
this->serverListener = new QTcpServer();
3、服務(wù)器監(jiān)聽
QHostAddress ipAddress(“192.168.1.1”);
quint16 ipPort = 8080;
serverListener->listen(ipAddress,ipPort);
4、聲明一個(gè)QList對(duì)象用于存客戶端
QList<QTcpSocket*> clientList;
5、連接信號(hào)與槽
QObject::connect(this->serverListener,SIGNAL(newConnection()),this,SLOT(newConnection()));//newConnection是自定義槽函數(shù),用于管理clientList列表
6、實(shí)現(xiàn)newConnection函數(shù),保存客戶端至clientList
void TcpServer::newConnection()
{
QTcpSocket* serverClient = this->serverListener->nextPendingConnection();//new出客戶端對(duì)象
this->clientList.append(serverClient);//保存
QObject::connect(serverClient,SIGNAL(readyRead()),this,SLOT(rcvData()));//當(dāng)此客戶端有數(shù)據(jù)時(shí)在自定義rcvData函數(shù)里接收
QObject::connect(serverClient,SIGNAL(disconnected()),this,SLOT(removeClient()));//當(dāng)此客戶端斷開連接時(shí),會(huì)發(fā)出disconnected信號(hào),在自定義removeClient里去除客戶端
}
7、實(shí)現(xiàn)removeClient函數(shù),去除客戶端
void TcpServer::removeClient()
{
for(int i=0;i<this->clientList.length();i++)
{
if(clientList.at(i)->socketDescriptor() == -1)//用于判斷當(dāng)前客戶端是否有效
clientList.removeAt(i);
}
}
8、實(shí)現(xiàn)rcvData函數(shù),接收數(shù)據(jù)
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、發(fā)送數(shù)據(jù)
clientList.at(n)->write(QByteArray ba);
10、停止
serverListener->close();
二、客戶端
1、聲明一個(gè)QTcpSocket對(duì)象
QTcpSocket* tcpClient;
2、new出對(duì)象
this->tcpClient = new QTcpSocket();
3、連接服務(wù)器,連接信號(hào)與槽
tcpClient->connectToHost("192.168.1.1","8080");
QObject::connect(this->tcpClient,SIGNAL(readyRead()),this,SLOT(rcvData()));//rcvData是自定義接收槽函數(shù)
4、實(shí)現(xiàn)rcvData函數(shù),接收數(shù)據(jù)
void TcpClient::rcvData()
{
QByteArray ba = tcpClient->readAll();
}
5、發(fā)送數(shù)據(jù)
tcpClient->write(QByteArray ba);
6、關(guān)閉
tcpClient->close();
ps:軟件開發(fā)流程
?
總結(jié)
- 上一篇: QT学习——Tcp客户端通信(本地回环)
- 下一篇: OpenCore 的代码结构