c++ qt获取电脑的内存_Qt官方示例-TCP客户端/服务器示例
生活随笔
收集整理的這篇文章主要介紹了
c++ qt获取电脑的内存_Qt官方示例-TCP客户端/服务器示例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
該示例演示了在本地主機上的TCP客戶端和服務器是如何通訊的。
客戶端
綁定信號槽。
connect(&tcpClient, &QAbstractSocket::connected, this, &Dialog::startTransfer); /* 連接到服務器時回送消息給服務器 */ connect(&tcpClient, &QIODevice::bytesWritten,this, &Dialog::updateClientProgress); /* 綁定寫數據到服務器的信號槽 */連接到服務器。
tcpClient.connectToHost(QHostAddress::LocalHost, tcpServer.serverPort());這里比較有意思的是,客戶端連接到服務器->客戶端(tcpClient)觸發startTransfer槽函數->調用tcpClient.write->觸發QIODevice::bytesWritten信號->觸發updateClientProgress槽函數調用->就一直tcpClient.write,直到if條件不成立后后停止發送。
void Dialog::startTransfer() {// called when the TCP client connected to the loopback serverbytesToWrite = TotalBytes - int(tcpClient.write(QByteArray(PayloadSize, '@')));clientStatusLabel->setText(tr("Connected")); } void Dialog::updateClientProgress(qint64 numBytes) {// called when the TCP client has written some bytesbytesWritten += int(numBytes);// only write more if not finished and when the Qt write buffer is below a certain size.if (bytesToWrite > 0 && tcpClient.bytesToWrite() <= 4 * PayloadSize) /* 直到if條件不成立后后停止發送 */bytesToWrite -= tcpClient.write(QByteArray(qMin(bytesToWrite, PayloadSize), '@'));clientProgressBar->setMaximum(TotalBytes);clientProgressBar->setValue(bytesWritten);clientStatusLabel->setText(tr("Sent %1MB").arg(bytesWritten / (1024 * 1024))); }服務端
綁定信號槽用于新連接:
connect(&tcpServer, &QTcpServer::newConnection,this, &Dialog::acceptConnection);監聽客戶端連接。
!tcpServer.isListening() && !tcpServer.listen()服務端新連接到來:
void Dialog::acceptConnection() {tcpServerConnection = tcpServer.nextPendingConnection();if (!tcpServerConnection) {serverStatusLabel->setText(tr("Error: got invalid pending connection!"));return;}connect(tcpServerConnection, &QIODevice::readyRead,this, &Dialog::updateServerProgress); /* 接受客戶端數據的槽函數 */connect(tcpServerConnection,QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::error),this, &Dialog::displayError); /* 錯誤反饋 */connect(tcpServerConnection, &QTcpSocket::disconnected,tcpServerConnection, &QTcpSocket::deleteLater); /* 斷開反饋 */serverStatusLabel->setText(tr("Accepted connection"));tcpServer.close(); }接收來自客戶端的數據:
void Dialog::updateServerProgress() {bytesReceived += int(tcpServerConnection->bytesAvailable());tcpServerConnection->readAll(); /* 讀數據 */serverProgressBar->setMaximum(TotalBytes);serverProgressBar->setValue(bytesReceived); /* 設置進度條 */serverStatusLabel->setText(tr("Received %1MB") /* 顯示在界面上 */.arg(bytesReceived / (1024 * 1024)));if (bytesReceived == TotalBytes) {tcpServerConnection->close();startButton->setEnabled(true); #ifndef QT_NO_CURSORQApplication::restoreOverrideCursor(); #endif} }關于更多
- 在QtCreator軟件可以找到:
- 或在以下Qt安裝目錄找到:
- 相關鏈接
- Qt君公眾號回復『Qt示例』獲取更多內容。
總結
以上是生活随笔為你收集整理的c++ qt获取电脑的内存_Qt官方示例-TCP客户端/服务器示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 优先队列priority_queue自定
- 下一篇: Java对象垃圾回收调用,JVM垃圾回收