c# (Unity)创建同步网络时间

本文关键字:同步网 网络 时间 同步 创建 Unity | 更新日期: 2023-09-27 18:13:56

我一直在讨论如何最终通过60个选定点同步20个对象的运动。我有几个选项,主要是

  • 使用同步变量在点(1到0)之间同步他们的进度,但这是开放的滞后和相当密集的
  • 使用unity内置的网络转换,但这在网络能力方面似乎代价高昂,因为其他设备只需要知道点和何时启动
  • 首先,发送点的列表,我已经成功地完成了,然后使设备在特定时间以固定速率开始运动

所以这就是我如何得出结论,我需要有一个联网的通用时间精确到0.1秒左右,这样用户就会看到同样的运动。如果你认为这是一种错误的社交方式,请告诉我,因为我只是一个社交初学者。

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

  1. 我使用System.DateTime相信它是准确和通用的时间,但发现设备之间的差异超过一秒

  2. 我试图计算两个设备之间的延迟,所以我可以计算并删除设备时间变化,通过

    • (A)使用GetAveragePing(NetworkPlayer player);的内置方法,但这是旧的和贬值的,因为NetworkPlayer类似乎不再功能和兼容
    • (B)使用GetCurrentRtt(int hostId, int connectionId, out byte error);的另一种内置方法,返回0,我认为可能再次贬值
    • (C)通过从服务器发送消息到客户端,然后将所花费的时间除以2,但这似乎不准确,因为我试图计算服务器和客户端之间的延迟,这与客户端和服务器之间的延迟不同,所以不完全是一半
  3. 我试图通过

    从服务器访问一种形式的同步网络时间
    • (A)使用代码从这里得到一个网络时间,然后计算出系统。DateTime与网络日期时间在某一点上的差异,以便我可以同步它们。下面是我用来做这件事的脚本:
    • (B)从GetNetworkTimestamp();获取网络时间戳,我认为这可能是我想要的

所以对于所有这些方法都失败了所以今天我问你;

  • 是否有其他同步时间的方法?

  • 这些方法中的一个应该工作,所以我错了,在这种情况下,我可以给我的问题和使用的代码的进一步细节?

  • 我的网络方法是完全错误的,或者至少大部分是错误的,你建议我如何实现我的预期目标?

非常感谢你阅读这篇文章,我希望它是详细的,仍然清楚,如果我能帮助你推进你对我的问题的理解,我将非常乐意协助。谢谢你的回答/有启发性的评论。

网络时间代码

脚本A(获取网络时间)

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(差分计算器和时间记录器)

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);
            }
        }
    }

c# (Unity)创建同步网络时间

…似乎只是加上时差而不是减去它可以工作并同步时间,所以不是

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

应该用

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

如果有人能证实这是/不是正确的建立人际关系的方法,我认为这是一个答案