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

使用REP文件定义远程对象
示例父目录中的REP文件“timemodel.rep”用于生成这两个应用程序共用的头文件。对于本应用程序,生成的“rep_timemodel_source.h”文件定义了MinuteTimerSource 、用于实现MinuteTimer 的派生类,以及其他相关类。
TimeModel 类
位于 timemodel.h 和 timemodel.cpp 中的TimeModel 类实现了待共享的时间对象。它使用QBasicTimer 来确保通过调用timerEvent 成员函数来更新时间。
voidMinuteTimer::timerEvent(QTimerEvent*)
{
QTime now=QTime::currentTime();
if(now.second()== 59&&now.minute()==time.minute()&&now.hour()==time.hour()) {
// 刚好错过了时间 tick 更新,强制触发,额外等待 0.5 秒
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 实例
创建QRemoteObjectHost 和QRemoteObjectRegistryHost 的实例用于托管对象,并建立注册表以便查找该对象。随后创建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();
}另请参阅 “时间客户端应用程序”。
© 2026 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.