一、前言
網絡調試助手和序列槽調試助手是一對的,用Qt開發項目與硬體通信絕大部分都是要麼序列槽通信(RS232 RS485 Modbus等),要麼就是網絡通信(TCP UDP HTTP等),是以一旦涉及到這兩方面,多多少少肯定離不開對應的調試助手協助進行程式的調試,尤其是硬體工程師,更加需要第三方的獨立的調試工具來驗證硬體工作是否正常,這可以大大避免扯皮的事情發生,既然第三方的工具測試下來沒有問題,收發資料都正常的話,那基本上可以斷定是軟體的問題,此時估計軟體工程師心裡慌得一逼啊!
基本功能:
- 16進制資料和ASCII資料收發。
- 定時器自動發送。
- 自動從配置檔案加載最後一次的界面設定。
- 自動從配置檔案加載資料發送下拉框的資料。可以将經常使用的資料填寫在send.txt中。
- 可啟用裝置模拟回複,當收到某個資料時,模拟裝置自動回複資料。對應資料格式填寫在device.txt中。
- 可對單個線上連接配接發送資料,也可勾選全部進行發送。
- 支援多個用戶端連接配接并發。
- 采用單線程。
- 四種模式,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;
}
}
}
}
}
三、效果圖
