时间服务器应用

与连接的客户端共享时间对象的服务器。

时间服务器应用程序实例化MinuteTimer 对象,并与所有连接的时间客户端应用程序共享。

使用 REP 文件定义远程对象

示例父目录中的 REP 文件 "timemodel.rep "用于生成两个应用程序使用的头文件。在此应用程序中,生成的 "rep_timemodel_source.h "文件定义了MinuteTimerSource (实现MinuteTimer 的子类)和其他相关类。

TimeModel 类

timemodel.h 和 timemodel.cpp 中的TimeModel 类实现了要共享的时间对象。它使用QBasicTimer 来确保通过调用timerEvent 成员函数来更新时间。

voidMinuteTimer::timerEvent(QTimerEvent*) { QTimenow=QTime::currentTime();if(now.second()== 59 &&now.minute()==time.minute()&&now.hour()==time.hour()) {// just missed time tick over, force it, wait extra 0.5 seconds time =time.addSecs(60); timer.start(60500, this); }else{ time=now; timer.start(60000-time.second()*1000, this);    }
    qDebug()<<"Time"<<time;
    setHour(time.hour()); setMinute(time.minute());emittimeChanged(); }

共享 TimeModel 实例

创建QRemoteObjectHostQRemoteObjectRegistryHost 的实例是为了托管一个对象,并有一个注册表来查找它。然后创建MinuteTimer 对象,并使用QRemoteObjectRegistryHost 对象的enableRemoting 成员函数共享该对象。

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    #if defined(Q_OS_UNIX) || defined(Q_OS_LINUX) || defined(Q_OS_QNX)
        signal(SIGINT, &unix_handler);
    #elif defined(Q_OS_WIN32)
        SetConsoleCtrlHandler((PHANDLER_ROUTINE)WinHandler, TRUE);
    #endif
    QRemoteObjectHost node(QUrl(QStringLiteral("local:replica")),QUrl(QStringLiteral("local:registry")));
    QRemoteObjectRegistryHost node2(QUrl(QStringLiteral("local:registry")));
    MinuteTimer timer;
    node2.enableRemoting(&timer);

    Q_UNUSED(timer)
    return app.exec();
}

示例项目 @ code.qt.io

另请参阅 时间客户端应用程序

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.