生活随笔
收集整理的這篇文章主要介紹了
Qt 网络编程制作一个客户端与服务器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
tcp服務器
使用 QtcpServer 與 QtcpSocket 類
使用QtcpServer、QtcpSocket類之前在項目的.pro文件中
添加 Qt += network
步驟
初始化一個QTcpServer 對象,注意初始化時傳入一個this指針
QTcpServer *tcpServer = new QTcpServer(this);
關聯newConnection信號,開啟監聽后,當一個新的連接接入,會發射newConnection信號,并使用關聯的newConnection_slot槽函數處理。
connect(tcpServer, &QTcpServer::newConnection, this, &TcpServer::newConnection_slot);
定義newConnection_slot槽函數
void TcpServer::newConnection_slot()
{// 使用 QTcpServer的nextPendingConnection方法獲取接入的QTcpSocket對象QTcpSocket* tcpSocket = tcpServer->nextPendingConnection(); // 使用QTcpSocket類的peerAddress和peerPort方法獲取客戶端ip地址和端口號QString socketName = QString("%1:%2").arg(tcpSocket->peerAddress().toString()).arg(tcpSocket->peerPort()); // tcpClients是一個QMap<QPair<QString, QTcpSocket *>> 類型的關聯容器,用于存儲當前接入的tcp連接if (!tcpClients.contains(socketName)) tcpClients.insert(socketName, tcpSocket);showMsg(QString("connect %1:%2").arg(tcpSocket->peerAddress().toString()).arg(tcpSocket->peerPort()));// 下拉框添加數據ui->selectSocketCb->addItem(socketName);// 關聯tcpSocket的readyRead和disconnected信號分別用對應的readyRead_slot、disconnected_slot槽函數處理connect(tcpSocket, &QTcpSocket::readyRead, this, &TcpServer::readyRead_slot);connect(tcpSocket, &QTcpSocket::disconnected, this, &TcpServer::disconnected_slot);
}
定義readyRead_slot槽函數
void TcpServer::readyRead_slot()
{// 使用QObject::sender()獲取當前發射信號的QTcpSocket對象QTcpSocket* tcpSocket = (QTcpSocket *)QObject::sender();QString buf;// 發送的數據使用QString類的 toLocal8Bit方法轉換為unicode編碼(于此對應toLatin1轉換為ASCII編碼),這里使用QTextCodec::codecForName("GB2312")->toUnicode()方法buf = QTextCodec::codecForName("GB2312")->toUnicode(tcpSocket->readAll());qDebug() << "recv " << buf;showMsg(QString("%1-> %2").arg(tcpSocket->localAddress().toIPv4Address()).arg(buf));
}
定義disconnected_slot槽函數
void TcpServer::disconnected_slot()
{QTcpSocket* tcpSocket = (QTcpSocket *)QObject::sender();QString socketName = QString("%1:%2").arg(tcpSocket->peerAddress().toString()).arg(tcpSocket->peerPort());tcpClients.remove(socketName);// qDebug() << "關閉";int index = ui->selectSocketCb->findText(socketName);if (index != -1) ui->selectSocketCb->removeItem(index);tcpSocket->deleteLater();showMsg(QString("%1 已斷開連接").arg(socketName));}
開啟監聽
void TcpServer::on_startBtn_clicked()
{if (ui->portEdit->text().isEmpty()){QMessageBox::warning(this, "警告", "端口號不能為空!", "確定");return ;}if (!tcpServer->isListening()){if (tcpServer->listen(QHostAddress::Any, ui->portEdit->text().toUInt())){showMsg(QString("服務器已開啟 %1 port %2").arg(tcpServer->serverAddress().toString()).arg(tcpServer->serverPort()));} else {showMsg("服務器開啟失敗: "+tcpServer->errorString());}ui->startBtn->setEnabled(false);ui->stopBtn->setEnabled(true);}}
tcp客戶端
// 初始化QTcpSocket實例
QTcpSocket *tcpSocket = new QTcpSocket(this);
// 中斷所有連接
tcpSocket->abort();
// 關聯connected信號
connect(tcpSocket, &QTcpSocket::connected, this, &TcpClient::connection_slot);
// 關聯 readyRead信號
connect(tcpSocket, &QTcpSocket::readyRead, this, &TcpClient::readyRead_slot);
// 連接到HOST
quint16 port = ui->portEdit->text().toUInt();
QString ip = ui->ipEdit->text();
tcpSocket->connectToHost(ip, port);
if (tcpSocket->waitForConnected(1000))
{showMsg("連接成功!");ui->closeBtn->setEnabled(true);ui->openBtn->setEnabled(false);ui->sendBtn->setEnabled(true);
} else {showMsg("連接失敗!");
}
connection_slot
void TcpClient::connection_slot()
{showMsg(QString("連接服務器 %1:%2").arg(tcpSocket->peerAddress().toString()).arg(tcpSocket->peerPort()));}
readyRead_slot
void TcpClient::readyRead_slot()
{QString buf = QTextCodec::codecForName("GB2312")->toUnicode(tcpSocket->readAll());qDebug() << "recv " << buf;showMsg(buf);
}
發送數據
void TcpClient::on_sendBtn_clicked()
{QString buf = ui->sendEdit->text();if (buf.isEmpty()){QMessageBox::warning(this, "警告", "發送內容不能為空!", "確定");return ;}qDebug() << "send msg " << buf;tcpSocket->write(buf.toLocal8Bit().data());ui->sendEdit->clear();}
總結
以上是生活随笔為你收集整理的Qt 网络编程制作一个客户端与服务器的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。