#ifndef HXUTILS_H #define HXUTILS_H #include #include #include #include #include #include #include #include #include #include #include #ifdef USE_RABBITMQ #include "qamqpclient.h" #include "qamqpexchange.h" #include "qamqpqueue.h" #endif /** * @brief Socket socket 工具类 */ class HxSocket : public QObject { Q_OBJECT public: HxSocket(quint16 port) { connect(&server, &QTcpServer::newConnection, this, &HxSocket::new_connection); server.listen(QHostAddress::Any, port); } HxSocket(QString address, int port) { is_reconnect = true; socket = new QTcpSocket(); connect(socket, &QTcpSocket::readyRead, this, &HxSocket::ready_read); connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()), Qt::QueuedConnection); connect(this, &HxSocket::reconnection_event, this, &HxSocket::reconnection); /* 域名解析 */ QHostInfo info = QHostInfo::fromName(address); this->port = port; this->address = info.addresses().at(0).toString(); reconnection(); } signals: void data_receive_event(QByteArray data); void reconnection_event(void); public slots: void new_connection() { if (socket != nullptr) socket->abort(); socket = server.nextPendingConnection(); connect(socket, &QTcpSocket::readyRead, this, &HxSocket::ready_read); connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()), Qt::QueuedConnection); } void write(QByteArray data) { if (socket == nullptr || socket->state() != QTcpSocket::ConnectedState) return; data.append('\n'); socket->write(data); socket->flush(); } void ready_read() { QByteArray msg = socket->readAll(); emit data_receive_event(msg.data()); } void disconnected() { if (is_reconnect) emit reconnection_event(); } /** * @brief 重连 */ void reconnection() { /* 取消已有的连接 */ if (socket != nullptr) socket->disconnectFromHost(); /* 连接服务器 */ socket->connectToHost(address, port); /* 等待连接 */ if (!socket->waitForConnected(500)) { auto time = QTime::currentTime().addMSecs(10000); while (QTime::currentTime() < time) QCoreApplication::processEvents(QEventLoop::AllEvents, 100); emit reconnection_event(); } } private: int port; QString address; bool is_reconnect = false; QTcpServer server; QTcpSocket *socket = nullptr; }; class HxDir { public: static bool mkpath(QString name) { return QDir().mkpath(name); } static void mkpath(QStringList names) { foreach (QString name, names) { HxDir::mkpath(name); } } static bool empty(QString name) { return QDir(name).removeRecursively(); } static double free_size(QString rootPath) { foreach (const QStorageInfo &storage, QStorageInfo::mountedVolumes()) { if (rootPath == storage.rootPath()) return static_cast(storage.bytesAvailable()) / 1024 / 1024 / 1024; } return 0; } }; class HxLog { public: static void append(QString title, QString message) { static QMutex mutex; mutex.lock(); auto current_time = QDateTime::currentDateTime(); QFile file(QString("log/%1.log").arg(current_time.toString("yyyyMMdd"))); if (file.open(QIODevice::WriteOnly | QIODevice::Append)) { auto data = QString("[%1] | [%2] | %3\r\n").arg(current_time.toString("yyyy-MM-dd HH:mm:ss"), title, message); file.write(data.toLocal8Bit()); file.close(); qDebug() << data; } mutex.unlock(); } }; class HxProcess { public: static QString start(QString command) { auto array = command.split(" "); QString program = array.at(0); QStringList arguments; for (int i = 1; i < array.count(); i++) arguments << array.at(i); QProcess process; process.setProcessChannelMode(QProcess::MergedChannels); process.start(program, arguments); process.waitForFinished(); return QString(process.readAll()); } }; #ifdef USE_RABBITMQ class HxRabbitMQ : public QObject { Q_OBJECT public: void set(QString host, QString username, QString password) { auto hosts = host.split(":"); client.setHost(hosts.at(0)); client.setPort(hosts.size() == 2 ? hosts.at(1).toInt() : 5672); client.setUsername(username); client.setPassword(password); client.setVirtualHost("/"); client.setAutoReconnect(true, 10); connect(&client, SIGNAL(connected()), this, SLOT(connected())); connect(&client, SIGNAL(disconnected()), this, SLOT(disconnected())); connect(this, &HxRabbitMQ::publish, this, &HxRabbitMQ::send_message); client.connectToHost(); } void set_exchanger_name(QString exchanger_name) { this->exchanger_name = exchanger_name; } void set_queue_name(QString queue_name) { this->queue_name = queue_name; } void set_routing_key(QString routing_key) { this->routing_key = routing_key; } private: void send_message(QString message) { QAmqpExchange *exchange = client.createExchange(exchanger_name); exchange->publish(message, routing_key); HxLog::append("RabbitMQ", QString("Key:%1 message:%2").arg(routing_key, message)); } signals: void publish(QString message); public slots: void connected() { HxLog::append("RabbitMQ", "connect success"); } void disconnected() { HxLog::append("RabbitMQ", "disconnect"); } private: QAmqpClient client; QString exchanger_name, queue_name, routing_key; }; #endif #endif // HXUTILS_H