## 一、前言
網路除錯助手和串列埠除錯助手是一對的,用Qt開發專案與硬體通訊絕大部分都是要麼串列埠通訊(RS232 RS485 Modbus等),要麼就是網路通訊(TCP UDP HTTP等),所以一旦涉及到這兩方面,多多少少肯定離不開對應的除錯助手協助進行程式的除錯,尤其是硬體工程師,更加需要第三方的獨立的除錯工具來驗證硬體工作是否正常,這可以大大避免扯皮的事情發生,既然第三方的工具測試下來沒有問題,收發資料都正常的話,那基本上可以斷定是軟體的問題,此時估計軟體工程師心裡慌得一逼啊!
基本功能:
1. 16進位制資料和ASCII資料收發。2. 定時器自動傳送。3. 自動從配置檔案載入最後一次的介面設定。4. 自動從配置檔案載入資料傳送下拉框的資料。可以將經常使用的資料填寫在send.txt中。5. 可啟用裝置模擬回覆,當收到某個資料時,模擬裝置自動回覆資料。對應資料格式填寫在device.txt中。6. 可對單個線上連線傳送資料,也可勾選全部進行傳送。7. 支援多個客戶端連線併發。8. 採用單執行緒。9. 四種模式,tcp客戶端、tcp伺服器、udp客戶端、udp伺服器。## 二、程式碼思路第一步:例項化對應的類tcpSocket = new QTcpSocket(this);connect(tcpSocket, SIGNAL(connected()), this, SLOT(connected()));connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(disconnected()));connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(disconnected()));connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readData()));tcpServer = new TcpServer(this);connect(tcpServer, SIGNAL(clientConnected(QString, int)), this, SLOT(clientConnected(QString, int)));connect(tcpServer, SIGNAL(clientDisconnected(QString, int)), this, SLOT(clientDisconnected(QString, int)));connect(tcpServer, SIGNAL(sendData(QString, int, QString)), this, SLOT(sendData(QString, int, QString)));connect(tcpServer, SIGNAL(receiveData(QString, int, QString)), this, SLOT(receiveData(QString, int, QString)));udpSocket = new QUdpSocket(this);connect(udpSocket, SIGNAL(readyRead()), this, SLOT(readData()));第二步:收發資料void frmTcpClient::readData(){ QByteArray data = tcpSocket->readAll(); if (data.length() <= 0) { return; } QString buffer; if (App::HexReceiveTcpClient) { buffer = QUIHelper::byteArrayToHexStr(data); } else if (App::AsciiTcpClient) { buffer = QUIHelper::byteArrayToAsciiStr(data); } else { buffer = QString(data); } append(1, buffer); //自動回覆資料,可以回覆的資料是以;隔開,每行可以帶多個;所以這裡不需要繼續判斷 if (App::DebugTcpClient) { int count = App::Keys.count(); for (int i = 0; i < count; i++) { if (App::Keys.at(i) == buffer) { sendData(App::Values.at(i)); break; } } }}void frmUdpClient::readData(){ QHostAddress host; quint16 port; QByteArray data; QString buffer; while (udpSocket->hasPendingDatagrams()) { data.resize(udpSocket->pendingDatagramSize()); udpSocket->readDatagram(data.data(), data.size(), &host, &port); if (App::HexReceiveUdpClient) { buffer = QUIHelper::byteArrayToHexStr(data); } else if (App::AsciiUdpClient) { buffer = QUIHelper::byteArrayToAsciiStr(data); } else { buffer = QString(data); } QString ip = host.toString(); ip = ip.replace("::ffff:", ""); if (ip.isEmpty()) { continue; } QString str = QString("[%1:%2] %3").arg(ip).arg(port).arg(buffer); append(1, str); if (App::DebugUdpClient) { int count = App::Keys.count(); for (int i = 0; i < count; i++) { if (App::Keys.at(i) == buffer) { sendData(ip, port, App::Values.at(i)); break; } } } }}
## 三、效果圖## 四、開源主頁1. 國內站點:[https://gitee.com/feiyangqingyun/QWidgetDemo](https://gitee.com/feiyangqingyun/QWidgetDemo)
2. 國際站點:[https://github.com/feiyangqingyun/QWidgetDemo](https://github.com/feiyangqingyun/QWidgetDemo)
最新評論