上一篇文章已經打通了數據源之一的串口採集,此次要說的是網絡採集,網絡通訊目前用的最多的是三種,TCP/UDP/HTTP,其中tcp通訊又包括了客戶端服務端兩種,tcp通訊才用了屢次握手機制不丟包,可是耗費資源多並且須要創建鏈接。udp通訊在大數據量或者網絡不穩定的狀況下,可能丟包,並且順序沒法保證,可是一個包的數據確定是正確的,因爲佔用資源極少並且不須要創建鏈接,在不少場景中應用也蠻多,我我的用udp以來,也沒發現過丟包的狀況,可能數據量不夠大或者是在局域網內的緣由吧,反正用起來仍是蠻爽的。http通訊目前很是流行,尤爲是和服務器之間作數據交互,基本上post請求而後返回一串json數據,解析對應的json數據便可。本次採用的TCP通訊做爲示例,其餘兩種能夠自行拓展,也很簡單的。linux
體驗地址:https://pan.baidu.com/s/1A5Gd77kExm8Co5ckT51vvQ 提取碼:877p 文件:可執行文件.zipc++
void frmData::initServer() { //實例化串口類,綁定信號槽 com = new QextSerialPort(QextSerialPort::EventDriven, this); connect(com, SIGNAL(readyRead()), this, SLOT(readDataCom())); //實例化網絡通訊客戶端類,綁定信號槽 tcpClient = new QTcpSocket(this); connect(tcpClient, SIGNAL(readyRead()), this, SLOT(readDataClient())); //實例化網絡通訊服務端類,綁定信號槽 tcpSocket = NULL; tcpServer = new QTcpServer(this); connect(tcpServer, SIGNAL(newConnection()), this, SLOT(newConnection())); //開啓定時器讀取數據庫採集數據 timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(readDataDb())); timer->setInterval(1000); } void frmData::on_btnOpenTcpClient_clicked() { if (ui->btnOpenTcpClient->text() == "鏈接") { tcpClient->connectToHost(App::TcpServerIP, App::TcpServerPort); bool ok = tcpClient->waitForConnected(1000); if (ok) { setEnable(ui->btnOpenTcpClient, false); ui->btnOpenTcpClient->setText("斷開"); } } else { tcpClient->disconnectFromHost(); setEnable(ui->btnOpenTcpClient, true); ui->btnOpenTcpClient->setText("鏈接"); } } void frmData::on_btnOpenTcpServer_clicked() { if (ui->btnOpenTcpServer->text() == "監聽") { #if (QT_VERSION > QT_VERSION_CHECK(5,0,0)) bool ok = tcpServer->listen(QHostAddress::AnyIPv4, App::TcpListenPort); #else bool ok = tcpServer->listen(QHostAddress::Any, App::TcpListenPort); #endif if (ok) { setEnable(ui->btnOpenTcpServer, false); ui->btnOpenTcpServer->setText("中止"); } } else { if (tcpSocket != NULL) { tcpSocket->disconnectFromHost(); } tcpSocket = NULL; tcpServer->close(); setEnable(ui->btnOpenTcpServer, true); ui->btnOpenTcpServer->setText("監聽"); } } void frmData::readDataClient() { QByteArray data = tcpClient->readAll(); if (data.length() <= 0) { return; } //默認取第一個字節解析,能夠自行更改 quint8 value = data.at(0); ui->txtValue->setText(QString::number(value)); append(3, data.toHex()); } void frmData::readDataServer() { QByteArray data = tcpSocket->readAll(); if (data.length() <= 0) { return; } //默認取第一個字節解析,能夠自行更改 quint8 value = data.at(0); ui->txtValue->setText(QString::number(value)); append(3, data.toHex()); } void frmData::newConnection() { while(tcpServer->hasPendingConnections()) { if (tcpSocket != NULL) { tcpSocket->disconnectFromHost(); } tcpSocket = tcpServer->nextPendingConnection(); connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readDataServer())); } }