简体   繁体   English

在C#游戏的网络代码中,我看到系统返回负数的问题。 谁能找到原因或提供改进?

[英]In net code for a C# game, I'm seeing an issue where the system is returning negatives. Can anyone spot why or offer improvements?

The main "Ping"/"Time" function for the game is this: 游戏的主要“ Ping” /“ Time”功能是这样的:

Net Code For Server - Time/Ping 服务器的净代码-时间/ ping

Outside of the switch, TimeSync() functions like this: 在开关之外,TimeSync()的功能如下:

private void TimeSync()
{
    YGConnection.Send("Time", DateTime.UtcNow.Millisecond);
}

It sends the current UTCNow.Millisecond time to the server. 它将当前的UTCNow.Millisecond时间发送到服务器。

Finally, getTime() gets the current time + the offset of the server. 最后,getTime()获取当前时间+服务器的偏移量。

private double getTime()
{
    return Math.Round((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds) + Offset;
}

It all works, but the numbers produced are like this: 都可以,但是产生的数字是这样的:

Version 0.1.5 : Server time offset: -486335789940 - Ping: -943491433067 版本0.1.5:服务器时间偏移:-486335789940-Ping:-943491433067

The server basically sends getTime() back, but without the offset. 服务器基本上将getTime()发送回去,但是没有偏移量。 I'm wondering what is going on with the negative numbers and if there is anything I can do to fix that. 我想知道负数是怎么回事,是否有什么办法可以解决。

DateTime.Milliseconds is the number of milliseconds (thousandths of a second) within the current second. DateTime.Milliseconds是当前秒内的毫秒数(千分之一秒)。 If you only compare Milliseconds, you will lose any information like the second it occurred in. 如果仅比较毫秒,则会丢失任何信息,例如发生的秒数。

At midnight it is 00:00:00.000 午夜是00:00:00.000

500 milliseconds later it is 00:00:00.500 500毫秒后是00:00:00.500

500 milliseconds later it is 00:00:01.000 500毫秒后是00:00:01.000

If you are just comparing the milliseconds, the difference between the first two times will be 500. 如果您只是比较毫秒,则前两次的差值为500。
The difference between the last two will be -500. 后两者之差为-500。

What you probably want to do is return a whole date/time value rather than just the milliseconds. 您可能想做的是返回一个完整的日期/时间值,而不只是毫秒。 If you subtract 2 DateTime objects, you get a TimeSpan object. 如果减去2个DateTime对象,则会得到一个TimeSpan对象。 From that you can find the TimeSpan.TotalMilliseconds will give you how many milliseconds there are between those two times regardless of how many seconds have elapsed. 从中可以找到TimeSpan.TotalMilliseconds将为您提供两次之间的毫秒数,而不管经过了多少秒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM