#ifndef HXUTILS_H #define HXUTILS_H #include #include #include #include #include #include #include /** * @brief SocketUtils socket 工具类 */ class HxSocketUtils : public QObject { Q_OBJECT public: HxSocketUtils(quint16 port) { connect(&server, &QTcpServer::newConnection, this, &HxSocketUtils::new_connection); server.listen(QHostAddress::Any, port); } HxSocketUtils(QString address, int port) { is_reconnect = true; socket = new QTcpSocket(); connect(socket, &QTcpSocket::readyRead, this, &HxSocketUtils::ready_read); connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()), Qt::QueuedConnection); connect(this, &HxSocketUtils::reconnection_event, this, &HxSocketUtils::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, &HxSocketUtils::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() { qDebug("socket disconnect"); if (is_reconnect) { qDebug("socket will be reconnected... "); emit reconnection_event(); } } /** * @brief 重连 */ void reconnection() { /* 取消已有的连接 */ if (socket != nullptr) { socket->disconnectFromHost(); qDebug("socket release"); } qDebug("socket connecting......"); /* 连接服务器 */ socket->connectToHost(address, port); /* 等待连接 */ if (socket->waitForConnected(500)) { qDebug("socket connect success"); } else { qDebug("socket connect failed"); /* 使用 QThread::msleep 延时,会使 Socket 出现接收不到事件信息 (槽无法响应) */ 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 HxProcessUtils { public: /** * */ static int execute(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); return QProcess::execute(program, arguments); } }; #endif // HXUTILS_H