mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QtNetwork/QTcpServer>
#include <QtNetwork/QTcpSocket>
#pragma comment(lib, "Qt5Networkd.lib")
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
void newConnect();
void readClient();
private:
Ui::MainWindow *ui;
QTcpServer *qtcpServer;
QTcpSocket *clientSocket;
QString m_sVersion;
QByteArray m_updateByteArray;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QMessageBox>
#define UPDATE_FILE_NAME ("ShutDownServer.exe")
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
qtcpServer = new QTcpServer(this);
clientSocket = new QTcpSocket(this);
// 监听是否有客户端连接
qtcpServer->listen(QHostAddress::Any, 6666);
connect(qtcpServer, SIGNAL(newConnection()), this, SLOT(newConnect()));
// 读取version.dat中的版本号
m_sVersion = "";
QFile file("version.dat");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug() << "Can't open the file!" << endl;
}
QByteArray line = file.readLine();
m_sVersion.append(line);
// 读取要更新的程序
QFile updateFile(UPDATE_FILE_NAME);
if (updateFile.open(QIODevice::ReadOnly))
{
m_updateByteArray = updateFile.readAll();
}
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::newConnect()
{
clientSocket = qtcpServer->nextPendingConnection();
connect(clientSocket, SIGNAL(readyRead()), this, SLOT(readClient()));
}
// 收到用户请求
void MainWindow::readClient()
{
quint64 ullWriteLen = 0u;
QString str = clientSocket->readAll();
std::string data = m_sVersion.toStdString();
if ("read version" == str)
{
clientSocket->write(data.c_str());
}
else if ("update" == str)
{
ullWriteLen = clientSocket->write(m_updateByteArray);
this->ui->textEdit->append("request from: " + clientSocket->peerAddress().toString());
this->ui->textEdit->append("filesize:" + QString::number(m_updateByteArray.size()) + " bytes, socket write length:" + QString::number(ullWriteLen) + " bytes");
}
}