天天看點

Qt 自動更新程式(用戶端)

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QtNetwork/QTcpSocket>
#include <QFile>
#include <QTimer>

#pragma comment(lib, "Qt5Networkd.lib")

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void update();

private:
    Ui::MainWindow *ui;

    QTcpSocket *qtcpUpdateSocket;
    QFile *file;
    QTimer *timer;
    QByteArray m_updateByteArray;
};

#endif // MAINWINDOW_H
           

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <ctime>
#include <QFile>
#include <QProcess>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    qtcpUpdateSocket = new QTcpSocket(this);
    qtcpUpdateSocket->abort();
    qtcpUpdateSocket->connectToHost("192.168.142.5", 6666);

    file = new QFile("recv.exe");
    file->open(QIODevice::ReadWrite);

    qtcpUpdateSocket->write("update");

    // 定時器
    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(update()));
    timer->start(1000);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::update()
{
    QByteArray readByteArray;
    QByteArray line;
    while (1)
    {
        line = qtcpUpdateSocket->readAll();
        if (line.length() == 0) break;
        readByteArray.append(line);
    }

    m_updateByteArray.append(readByteArray);

    this->ui->textEdit->append("download file: " + QString::number(readByteArray.length()) + " bytes");

    if (0 == readByteArray.length())
    {
        this->ui->textEdit->append("write data to file...");
        file->write(m_updateByteArray);
        this->ui->textEdit->append("write " + QString::number(m_updateByteArray.length()) + " bytes to file.");

        // 删除舊的檔案
        QFile::remove("ShutDownServer.exe");
//        QFile oldfile("ShutDownServer.exe");
//        if (oldfile.open(QIODevice::ReadWrite))
//        {
//            if (oldfile.exists())
//            {
//                oldfile.remove();
//            }
//        }
//        oldfile.close();

        // 重命名新檔案
        file->rename("ShutDownServer.exe");
        this->ui->textEdit->append("rename file");
        file->close();

        if (QProcess::startDetached("ShutDownServer.exe"))
        {
            exit(1);
        }
        timer->stop();
    }

}