首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C# (统一)创建同步网络时间

C# (统一)创建同步网络时间
EN

Stack Overflow用户
提问于 2016-10-20 15:20:48
回答 1查看 3.5K关注 0票数 1

我一直在围绕着如何通过60个选择点最终同步20个物体的运动而旋转。我有几个主要的选择

  • 使用同步vars同步点之间的进度(1到0),但这是开放的滞后和相当密集的。
  • 使用内置于网络转换中的统一,但就联网能力而言,这似乎很昂贵,因为其他设备只需要知道点和何时开始
  • 首先,发送点列表,这是我成功完成的,然后使设备在一定的时间以固定的速度开始移动。

这就是我得出的结论,我需要有一个网络世界的时间精确到0.1秒左右,这样用户才能看到同样的运动。如果你认为这是一个错误的方法,请告诉我,因为我是一个网络初学者。

到目前为止,我已经尝试了三种方法来获得这个同步的时间。

  1. 我使用System.DateTime,相信这是一个准确和普遍的时间,但在设备之间发现了超过一秒的变化。
  2. 我试图计算这两个设备之间的延迟,以便计算并消除设备时间的变化。
代码语言:javascript
复制
- (A) Using the in built method of `GetAveragePing(NetworkPlayer player);` but this was old and depreciated as the NetworkPlayer class seemed to be no longer functional and compatible
- (B) Using another in built method of `GetCurrentRtt(int hostId, int connectionId, out byte error);` which returned 0 and again i believe may be depreciated
- (C) By sending a message from the Server to the Client and back then dividing the time taken by two but this seemed inaccurate as I was trying to calculate latency between the server and client which was not the same as between the client and server so not exactly half

  1. 我试图从服务器访问一种形式的同步网络时间,通过
代码语言:javascript
复制
- (A) Using code from [here](https://stackoverflow.com/questions/1193955/how-to-query-an-ntp-server-using-c) to get a network time then worked out the System.DateTime difference between the network date time at a certain point so that i could synchronize them. The scripts which I used to do this are below.
- (B) Getting network time stamps from `GetNetworkTimestamp();` which I thought may be what i wanted

所以所有这些方法都失败了,所以今天我请求你们;

  • 还有其他同步时间的方法吗?
  • 这些方法中的一个应该有效吗?那么,我是否出错了?在这种情况下,我可以进一步详细说明我的问题和使用的代码。
  • 我的社交方式是完全错误的,或者至少大部分是错误的,你建议我如何实现我想要的目标?

非常感谢你阅读了这篇文章,我希望它是详细和清晰的,如果我能帮助你提高你对我的问题的理解,我将非常乐意提供帮助。谢谢你的回答/启发意见。

网络时间代码

脚本A(获取网络时间)

代码语言:javascript
复制
using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using UnityEngine.UI;
public class GetNetworkTime : MonoBehaviour {

    public static System.DateTime NetworkTime()
    {
        //default Windows time server
        const string ntpServer = "time.windows.com";

        // NTP message size - 16 bytes of the digest (RFC 2030)
        var ntpData = new byte[48];

        //Setting the Leap Indicator, Version Number and Mode values
        ntpData[0] = 0x1B; //LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode)

        var addresses = Dns.GetHostEntry(ntpServer).AddressList;

        //The UDP port number assigned to NTP is 123
        var ipEndPoint = new IPEndPoint(addresses[0], 123);
        //NTP uses UDP
        var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

        socket.Connect(ipEndPoint);

        //Stops code hang if NTP is blocked
        socket.ReceiveTimeout = 3000;

        socket.Send(ntpData);
        socket.Receive(ntpData);
        socket.Close();

        //Offset to get to the "Transmit Timestamp" field (time at which the reply 
        //departed the server for the client, in 64-bit timestamp format."
        const byte serverReplyTime = 40;

        //Get the seconds part
        ulong intPart = System.BitConverter.ToUInt32(ntpData, serverReplyTime);

        //Get the seconds fraction
        ulong fractPart = System.BitConverter.ToUInt32(ntpData, serverReplyTime + 4);

        //Convert From big-endian to little-endian
        intPart = SwapEndianness(intPart);
        fractPart = SwapEndianness(fractPart);

        var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);

        //**UTC** time
        var networkDateTime = (new System.DateTime(1900, 1, 1, 0, 0, 0, System.DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);

        //return networkDateTime.ToLocalTime();
        return networkDateTime;
    }

    // stackoverflow.com/a/3294698/162671
    static uint SwapEndianness(ulong x)
    {
        return (uint)(((x & 0x000000ff) << 24) +
                       ((x & 0x0000ff00) << 8) +
                       ((x & 0x00ff0000) >> 8) +
                       ((x & 0xff000000) >> 24));
    }
}

脚本B(差分计算器和时间记录器)

代码语言:javascript
复制
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
using UnityEngine.UI;

    public class SyncTime2 : NetworkBehaviour {

        public float serverTimeDif;
        public float clientTimeDif;

        GetNetworkTime GetNetworkTime;

        GameObject time;
        Text TimeLog;

        // Use this for initialization
        void Start () {
            GetNetworkTime = GetComponent<GetNetworkTime>();
            time = GameObject.Find("time");
            TimeLog = time.GetComponent<Text>();
            if (isServer)
            {
                serverTimeDif = (float)System.DateTime.UtcNow.TimeOfDay.TotalSeconds - (float) GetNetworkTime.NetworkTime().TimeOfDay.TotalSeconds;
                StartCoroutine("DisplayTime", serverTimeDif);
            }
            else
            {
                clientTimeDif = (float)System.DateTime.UtcNow.TimeOfDay.TotalSeconds - (float)GetNetworkTime.NetworkTime().TimeOfDay.TotalSeconds;
                StartCoroutine("DisplayTime", clientTimeDif);
            }
        }

        IEnumerator DisplayTime (float TimeDif)
        {
            for (;;)
            {
                TimeLog.text = "" + ((float)System.DateTime.UtcNow.TimeOfDay.TotalSeconds + TimeDif);
                // Log time so i can see if it is different on different devices
                yield return new WaitForSeconds(0.01f);
            }
        }
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-10-20 17:09:28

嗯..。似乎只是简单地增加时差而不是减去它的工作和同步时间,所以

TimeLog.text = "" + ((float)System.DateTime.UtcNow.TimeOfDay.TotalSeconds - TimeDif);

我应该用

TimeLog.text = "" - ((float)System.DateTime.UtcNow.TimeOfDay.TotalSeconds + TimeDif);

如果有人能确认这是/不是正确的联网方法,我就认为这是一个答案。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40158468

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档