基于Qt编写通过TCP协议构建客户端和服务器,然后读取温度,存入SQLite数据库的代码
时间: 2024-02-18 21:04:53 浏览: 86
基于TCP的QT电子词典
好的,以下是一个简单的基于Qt通过TCP协议构建客户端和服务器,然后读取温度,存入SQLite数据库的示例代码:
服务器端代码:
```c++
#include <QTcpServer>
#include <QTcpSocket>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QDateTime>
int main(int argc, char *argv[])
{
QTcpServer server;
if (!server.listen(QHostAddress::Any, 1234)) {
qDebug() << "Failed to start server:" << server.errorString();
return -1;
}
qDebug() << "Server started";
// 连接SQLite数据库
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("temperature.db");
if (!db.open()) {
qDebug() << "Failed to open database:" << db.lastError().text();
return -1;
}
// 创建温度表
QSqlQuery query;
if (!query.exec("CREATE TABLE IF NOT EXISTS temperature (datetime DATETIME, value REAL)")) {
qDebug() << "Failed to create table:" << query.lastError().text();
return -1;
}
while (true) {
QTcpSocket *client = server.nextPendingConnection();
qDebug() << "Client connected:" << client->peerAddress().toString();
// 读取温度
float temperature = ...;
// 获取当前时间
QDateTime now = QDateTime::currentDateTime();
// 插入温度数据
query.prepare("INSERT INTO temperature (datetime, value) VALUES (?, ?)");
query.addBindValue(now);
query.addBindValue(temperature);
if (!query.exec()) {
qDebug() << "Failed to insert data:" << query.lastError().text();
client->write("Error");
} else {
client->write("OK");
}
client->disconnectFromHost();
client->deleteLater();
}
return 0;
}
```
客户端代码:
```c++
#include <QTcpSocket>
int main(int argc, char *argv[])
{
QTcpSocket socket;
socket.connectToHost("127.0.0.1", 1234);
if (!socket.waitForConnected()) {
qDebug() << "Failed to connect to server:" << socket.errorString();
return -1;
}
qDebug() << "Connected to server";
// 发送请求
socket.write("Get temperature");
// 等待服务器返回数据
if (!socket.waitForReadyRead()) {
qDebug() << "Failed to receive data:" << socket.errorString();
return -1;
}
// 处理服务器返回的数据
QString result = socket.readAll();
if (result == "OK") {
qDebug() << "Temperature data saved";
} else {
qDebug() << "Failed to save temperature data";
}
socket.disconnectFromHost();
return 0;
}
```
上述示例代码中的 `...` 部分需要替换成读取温度的实际代码。另外,为了使示例代码更加完整,我们还需要在程序中添加相关的头文件和其他必要的代码。希望以上代码能够对您有所帮助。
阅读全文