码迷,mamicode.com
首页 > Windows程序 > 详细

c# Internet时间服务器同步

时间:2015-11-12 01:11:34      阅读:490      评论:0      收藏:0      [点我收藏+]

标签:

 

 

需要用到的名空间

 

[c-sharp] view plaincopy
 
  1. using System.Net;  
  2. using System.Net.Sockets;  
  3. using System.Runtime.InteropServices;   

 

 

建立一个结构

 

[c-sharp] view plaincopy
 
  1. public struct SystemTime  
  2.         {  
  3.             public ushort wYear;  
  4.             public ushort wMonth;  
  5.             public ushort wDayOfWeek;  
  6.             public ushort wDay;  
  7.             public ushort wHour;  
  8.             public ushort wMinute;  
  9.             public ushort wSecond;  
  10.             public ushort wMilliseconds;  
  11.   
  12.             /// <summary>  
  13.             /// 从System.DateTime转换。  
  14.             /// </summary>  
  15.             /// <param name="time">System.DateTime类型的时间。</param>  
  16.             public void FromDateTime(DateTime time)  
  17.             {  
  18.                 wYear = (ushort)time.Year;  
  19.                 wMonth = (ushort)time.Month;  
  20.                 wDayOfWeek = (ushort)time.DayOfWeek;  
  21.                 wDay = (ushort)time.Day;  
  22.                 wHour = (ushort)time.Hour;  
  23.                 wMinute = (ushort)time.Minute;  
  24.                 wSecond = (ushort)time.Second;  
  25.                 wMilliseconds = (ushort)time.Millisecond;  
  26.             }  
  27.             /// <summary>  
  28.             /// 转换为System.DateTime类型。  
  29.             /// </summary>  
  30.             /// <returns></returns>  
  31.             public DateTime ToDateTime()  
  32.             {  
  33.                 return new DateTime(wYear, wMonth, wDay, wHour, wMinute, wSecond, wMilliseconds);  
  34.             }  
  35.             /// <summary>  
  36.             /// 静态方法。转换为System.DateTime类型。  
  37.             /// </summary>  
  38.             /// <param name="time">SYSTEMTIME类型的时间。</param>  
  39.             /// <returns></returns>  
  40.             public static DateTime ToDateTime(SystemTime time)  
  41.             {  
  42.                 return time.ToDateTime();  
  43.             }  
  44.         }  

 

要用到Windows的API函数来设置系统时间

 

[c-sharp] view plaincopy
 
  1. public class Win32API  
  2.         {  
  3.             [DllImport("Kernel32.dll")]  
  4.             public static extern bool SetLocalTime(ref SystemTime Time);  
  5.             [DllImport("Kernel32.dll")]  
  6.             public static extern void GetLocalTime(ref SystemTime Time);  
  7.         }  

 

用Socket获取Internet时间服务器上的时间

 

[c-sharp] view plaincopy
 
  1. public void SetInternetTime()  
  2.         {  
  3.             // 记录开始的时间  
  4.             DateTime startDT = DateTime.Now;  
  5.   
  6.             //建立IPAddress对象与端口,创建IPEndPoint节点:  
  7.             int port = 13;  
  8.             string[] whost = { "5time.nist.gov", "time-nw.nist.gov", "time-a.nist.gov", "time-b.nist.gov", "tick.mit.edu", "time.windows.com", "clock.sgi.com" };  
  9.               
  10.             IPHostEntry iphostinfo;  
  11.             IPAddress ip;  
  12.             IPEndPoint ipe;  
  13.             Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建Socket  
  14.   
  15.             c.ReceiveTimeout = 10 * 1000;//设置超时时间  
  16.   
  17.             string sEX = "";// 接受错误信息  
  18.   
  19.             // 遍历时间服务器列表  
  20.             foreach (string strHost in whost)  
  21.             {  
  22.                 try  
  23.                 {  
  24.                     iphostinfo = Dns.GetHostEntry(strHost);  
  25.                     ip = iphostinfo.AddressList[0];  
  26.                     ipe = new IPEndPoint(ip, port);  
  27.   
  28.                     c.Connect(ipe);//连接到服务器  
  29.                     if (c.Connected) break;// 如果连接到服务器就跳出  
  30.                 }  
  31.                 catch (Exception ex)  
  32.                 {  
  33.                     sEX = ex.Message;  
  34.                 }  
  35.             }  
  36.   
  37.             if (!c.Connected)  
  38.             {  
  39.                 MessageBox.Show("时间服务器连接失败!/r错误信息:" + sEX, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);  
  40.                 return;  
  41.             }  
  42.   
  43.             //SOCKET同步接受数据  
  44.             byte[] RecvBuffer = new byte[1024];  
  45.             int nBytes, nTotalBytes = 0;  
  46.             StringBuilder sb = new StringBuilder();  
  47.             System.Text.Encoding myE = Encoding.UTF8;  
  48.   
  49.             while ((nBytes = c.Receive(RecvBuffer, 0, 1024, SocketFlags.None)) > 0)  
  50.             {  
  51.                 nTotalBytes += nBytes;  
  52.                 sb.Append(myE.GetString(RecvBuffer, 0, nBytes));  
  53.             }  
  54.              
  55.             //关闭连接  
  56.             c.Close();  
  57.               
  58.             string[] o = sb.ToString().Split(‘ ‘); // 打断字符串  
  59.   
  60.             textBox1.Text = sb.ToString();  
  61.   
  62.             TimeSpan k = new TimeSpan();  
  63.             k = (TimeSpan)(DateTime.Now - startDT);// 得到开始到现在所消耗的时间  
  64.   
  65.             DateTime SetDT = Convert.ToDateTime(o[1] + " " + o[2]).Subtract(-k);// 减去中途消耗的时间  
  66.   
  67.             //处置北京时间 +8时  
  68.             SetDT = SetDT.AddHours(8);  
  69.   
  70.             //转换System.DateTime到SystemTime  
  71.             SystemTime st = new SystemTime();  
  72.             st.FromDateTime(SetDT);  
  73.   
  74.             //调用Win32 API设置系统时间  
  75.             Win32API.SetLocalTime(ref st);  
  76.   
  77.             MessageBox.Show("时间已同步", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);  
  78.         }  
   

 

 

这个东西是收集网上的一些做法再修改了一下

用vs2008+windows xp sp2测试通过

但是始终会有±1秒的误差,但大部分误差在1秒以下,尚可接受

使用的名空间包括vs自己添加的,windows Form中用到的那部分

如果换了环境,可作相应修改

转载:http://blog.csdn.net/zhengxia19/article/details/3858910

c# Internet时间服务器同步

标签:

原文地址:http://www.cnblogs.com/czg1046726286/p/4957731.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!