将移动设备与服务器同步以在多个移动设备上同时执行 运行 命令

Sync mobile device with server to run command at the same time across many mobile devices

我正在为健身设备(通过 BLE)的移动设备构建一个实时竞争应用程序。由于延迟,移动设备可以在不同时间从服务器接收命令。我正在尝试实现所有设备与服务器“同步”并同时执行“开始比赛”命令的目标。这样,不一定彼此相邻的用户将获得尽可能接近实时的体验,并在接近准确的时刻开始竞争。此时我使用 WebSockets 向我的移动应用程序发布命令,但假设设备 A 将在 20 毫秒内收到它,设备 B 将在 150 毫秒内收到它。尽管这只是一眨眼的功夫,但在健身器材上却非常引人注目。我如何在架构上制作一个应用程序,例如在世界标准时间下午 1 点在所有设备上执行命令?这里的问题是移动设备可能有不同的时间,所以我希望我的移动应用程序与服务器时间同步,如果我说在 UTC 服务器时间下午 1 点执行命令,我知道所有移动设备都会实现这一点。

当前架构:

schedule or manually invoked command -> SignalR notifies all connected devices -> devices execute "start"

可能的架构:

schedule or manually invoked command let devices know the exact time to run command -> SignalR (WebSockets or some other technology) notify connected device to sync mobile app time with server and command execution time -> Command is executed in near real-time across many devices

如何同步时间?使用NTP?您认为这种情况下的最佳架构是什么?

我见过许多与此类似的应用程序,但我正在尝试了解其架构。我认为技术无关紧要,我无法控制健身设备上的 BLE 执行时间,但它们很快。如果它有助于我将 SignalR 用于 WebSocket(C# 中的 .NET Core 3.x),移动应用程序是 运行 on Flutter/Dart。

要同步时间,您可以使用 toUtc method

Returns this DateTime value in the UTC time zone.

然后在所有设备上同时启动它使用 Timer

Creates a new timer. The callback function is invoked after the given duration.

下面的工作示例:

import 'dart:core';

DateTime startTime = DateTime.utc(2021, 2, 16, 15, 0); // you feed the startTime from your server using websocket.

void checkForStart(Timer timer) {
  print(startTime);
  timer?.cancel();
  while (true) {
    print('Run Forest!');
    // [... do your app things]
  }
}

...

 initState() {
    super.initState();

    var current = DateTime.now().toUtc(); // this is what you want
    Duration difference = startTime.difference(current);
    timer = Timer(Duration(microseconds: difference.inMicroseconds), () => checkForStart(timer));
[...]

dispose() {
    timer?.cancel();
    super.dispose();
  }

输出:

I/flutter ( 5819): 2021-02-16 15:00:00.000Z
I/flutter ( 5819): Run Forest!
I/chatty  ( 5819): uid=10154() 1.ui identical 65535 lines
I/flutter ( 5819): Run Forest!

此代码将保证该应用程序对所有人同时启动,因为它会使用计时器执行检查并在您向设备提供的 startTime 启动时间的同时在本地设备上启动它(注意:此是前台版本,意味着每个人都应该打开应用程序)

我没有详细介绍 websocket 部分,因为我假设您可以毫无问题地实现它,如果没有,您可以查看 this repository 或不同的文档、教程和 Whosebug 答案。如果有帮助,请告诉我。