C# Winform小程序:局域網設置NTP服務器、實現時間同步

  • 設置NTP服務器:

NTP是網絡時間協議(Network Time Protocol),它是用來同步網絡中各個計算機的時間的協議。服務器

局域網不能鏈接Internet,能夠設置一臺計算機爲NTP服務器。網絡

  • 依次點擊:開始---運行---regedit,進入註冊表;
  • 依次展開:HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer,在NtpServer項右側鍵值Enablied,默認值0改成1,1爲啓動NTP服務器;

 

  • 依次展開:HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Config,在Config項右側鍵值AnnounceFlags,默認值10改成5,5表明自身爲可靠時間源;

  • 修改完成以上關閉註冊表;
  • 命令行輸入:net stop w32Time,回車,中止NTP服務;
  • 命令行輸入:net start w32Time,回車,啓動NTP服務;
  • 當前計算機設置NTP服務器完成。
  • 局域網內其餘電腦命令行輸入:net time \\10.30.100.119 /set /yes,實現時間同步,其中10.30.100.119表明NTP服務器地址。
  • C# Winform實現局域網時間同步demo:

全局變量:app

//Timer
System.Timers.Timer timer = new System.Timers.Timer(); //IP
private string ipAddress; //時間間隔
private int timeInterval; //建立bat文件路徑,若是存在,直接覆蓋
private string filePath = System.Environment.CurrentDirectory + @"\timesync.bat";

頁面Load方法:ide

private void FrmMain_Load(object sender,EventArgs e) { //運行標誌隱藏
      picRun.Visible = false; }

Run/Abort按鈕點擊事件:ui

private void btnRunAbort_Click(object sender,EventArgs e) { //IP
      ipAddress = txtIP.Text.Trim(); //Time Interval
      timeInterval = Convert.ToInt32(txtTimeInterval.Text); if (btnRunAbort.Text.Equals("開始同步")) { this.RunTimer(); } else if (btnRunAbort.Text.Equals("中止同步")) { //定時器中止
 timer.Stop(); timer = new System.Timers.Timer(); MessageBox.Show("中止同步成功","提示"); //運行標誌隱藏
            picRun.Visible = false; btnRunAbort.Text = "開始同步"; } }

開始同步執行方法:this

public void RunTimer() { //建立bat文件
      FileStream fs = new FileStream(filePath, FileMode.Create,FileAccess.Write); StreamWriter sw = new StreamWriter(fs); sw.WriteLine(string.Format(@"net time \\{0} /set /yes",ipAddress)); sw.Close(); fs.Close(); try { //執行時間超過10秒,強制結束
            if (!CallWithTimeOut(CommonRun,10000)) { MessageBox.Show("服務器異常!","提示"); return; } //服務器地址異常
            if (StringRun().EndsWith(@"/yes")) { MessageBox.Show("服務器異常!","提示"); return; } MessageBox.Show("開始同步成功!","提示"); //BeginInvoke
            SetPBState(true , "中止同步"); } catch (Exception ex) { MessageBox.Show("服務器異常!","提示"); return; } //timer定時器執行時間同步
      timer.Elapsed += new System.ElapsedEventHandle(TimerRun); timer.Enabled = true; timer.Interval = Convert.ToInt32(txtTimeInterval.Text) * 1000; timer.Start(); }

 時間同步,返回執行bat輸出:spa

private string StringRun() { ProcessStartInfo pro = new ProcessStartInfo("cmd.exe"); pro.UseShellExecute = false; pro.RedirectStandardOutput = true; pro.RedirectStandardError = true; pro.CreateNoWindow = true; pro.FileName = filePath; pro.WorkingDirectory = System.Environment.CurrentDirectory; Process proc = new Process.Start(pro); StreamReader sOutput = proc.StandardOutput; proc.Close(); string sJudge = sOutput.ReadToEnd().Trim(); sOutput.Close(); return sJudge; }

時間同步:命令行

private void CommonRun() { ProcessStartInfo pro = new ProcessStartInfo("cmd.exe"); pro.UseShellExecute = false; pro.RedirectStandardOutput = true; pro.RedirectStandardError = true; pro.CreateNoWindow = true; pro.FileName = filePath; pro.WorkingDirectory = System.Environment.CurrentDirectory; Process proc = new Process.Start(pro); StreamReader sOutput = proc.StandardOutput; proc.Close(); string sJudge = sOutput.ReadToEnd().Trim(); sOutput.Close(); }

timer定時器時間同步:code

private void TimerRun(object source , System.Timers.ElapsedEventArgs e) { ProcessStartInfo pro = new ProcessStartInfo("cmd.exe"); pro.UseShellExecute = false; pro.RedirectStandardOutput = true; pro.RedirectStandardError = true; pro.CreateNoWindow = true; pro.FileName = filePath; pro.WorkingDirectory = System.Environment.CurrentDirectory; Process proc = new Process.Start(pro); StreamReader sOutput = proc.StandardOutput; proc.Close(); string sJudge = sOutput.ReadToEnd().Trim(); sOutput.Close(); }

deletegate InvokeRequired:orm

delegate void DelegatePBUpdate(bool b , string btnText); public void SetPBState(bool b , string btnText) { if (this.InvokeRequired) { this.BeginInvoke(new DelegatePBUpdate(SetPBState), new object[] {b , btnText}); } else { picRun.Visible = true; btnRunAbort.Text = "中止同步"; } }

方法執行時間超過設定值,強制結束:

static bool CallWithTimeout(Action action, int timeoutMilliseconds) { Thread threadToKill = null; Action wrappedAction = () => { threadToKill = Thread.CurrentThread; action(); } IAsyncResult result = wrappedAction.BeginInvoke(null, null); if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds)) [ wrappedAction.EndInvoke(result); return true; ] else { threadToKill.Abort(); return false; } }
  • 運行結果:

相關文章
相關標籤/搜索