简体   繁体   English

我想知道如何使用C#中的序列化检查tcp客户端服务器的经过时间

[英]I would like to know how to check the elapsed time with tcp client server using serialization in C#

I need to know how to check properly the elapsed time of sending messages between two clients and 1 server. 我需要知道如何正确检查两个客户端和一台服务器之间发送消息的时间。

I tried to put in my object that I transfer the the exact time in milliseconds with the next function: 我试图用下一个函数放入我要传输的精确时间(以毫秒为单位)的对象:

class exactTime {
  public static double ConvertSecondsToMilliseconds() {
    return TimeSpan.FromSeconds(DateTime.Now.Second).TotalMilliseconds;
  }
  public static double ConvertMinutesToMilliseconds() {
    return TimeSpan.FromMinutes(DateTime.Now.Minute).TotalMilliseconds;
  }
  public static double ConvertHoursToMilliseconds() {
    return TimeSpan.FromHours(DateTime.Now.Hour).TotalMilliseconds;
  }
  public static double ExactTime() {
    double exacatTime = DateTime.Now.Millisecond + ConvertHoursToMilliseconds() + 
       ConvertMinutesToMilliseconds() + ConvertSecondsToMilliseconds();
    return exacatTime;
  }
}

than when I recieve the message I use the same function than I subtracting what I got with the time that I got in the object that I got but the output isnt good, its allways grow and its make no scence. 比起我收到消息时,我使用了相同的函数,而不是减去我在获得的对象中得到的时间后得到的结果,但是输出效果不好,它总是增长并且没有任何作用。 like that: 像那样:

double remainderTime = exactTime.ExactTime() - tcpObject.exactTime;

This cannot be easily done, because server and client will probably have different time. 这不容易做到,因为服务器和客户端可能会有不同的时间。 This happens because internal clock of computers drift, and each one of them drift differently. 发生这种情况是因为计算机的内部时钟漂移,并且每个计算机的漂移都不同。 Over a month a difference of several seconds can accumulate. 一个月内可能会累积几秒钟的差异。

If you control server and clients, then you can set up NTP-based time synchronization with a reliable source, but this is more of administrative, then programming task. 如果控制服务器和客户端,则可以使用可靠的源设置基于NTP的时间同步,但这更多的是管理工作,然后是编程任务。

As an alternative, you can try to implement time-synchronization at your application level, so that client can determine offset from server time. 或者,您可以尝试在应用程序级别实现时间同步,以便客户端可以确定与服务器时间的偏移量。 Take a look at NTP protocol for inspiration. 看一下NTP协议的灵感。

Also, all this fiddling with DateTime.Now does not improve precision, and can be replaced with just DateTime.Now.Ticks. 同样,所有这些与DateTime.Now一起摆弄的东西也不能提高精度,可以仅用DateTime.Now.Ticks代替。 Keep in mind, that DateTime.Now have a 10 millisecond resolution, which is bigger than a clien-server roundtrip on the local network. 请记住,DateTime.Now现在具有10毫秒的分辨率,比本地网络上的客户端服务器往返更大。

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

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