简体   繁体   中英

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.

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.

Also, all this fiddling with DateTime.Now does not improve precision, and can be replaced with just 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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