C# Winform小程序:局域网设置NTP服务器、实现时间同步
生活随笔
收集整理的這篇文章主要介紹了
C# Winform小程序:局域网设置NTP服务器、实现时间同步
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
- 設(shè)置NTP服務(wù)器:
NTP是網(wǎng)絡(luò)時(shí)間協(xié)議(Network Time Protocol),它是用來(lái)同步網(wǎng)絡(luò)中各個(gè)計(jì)算機(jī)的時(shí)間的協(xié)議。
局域網(wǎng)不能連接Internet,可以設(shè)置一臺(tái)計(jì)算機(jī)為NTP服務(wù)器。
- 依次點(diǎn)擊:開(kāi)始---運(yùn)行---regedit,進(jìn)入注冊(cè)表;
- 依次展開(kāi):HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer,在NtpServer項(xiàng)右側(cè)鍵值Enablied,默認(rèn)值0改為1,1為啟動(dòng)NTP服務(wù)器;
?
- 依次展開(kāi):HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Config,在Config項(xiàng)右側(cè)鍵值A(chǔ)nnounceFlags,默認(rèn)值10改為5,5代表自身為可靠時(shí)間源;
- 修改完成以上關(guān)閉注冊(cè)表;
- 命令行輸入:net stop w32Time,回車(chē),停止NTP服務(wù);
- 命令行輸入:net start w32Time,回車(chē),啟動(dòng)NTP服務(wù);
- 當(dāng)前計(jì)算機(jī)設(shè)置NTP服務(wù)器完成。
- 局域網(wǎng)內(nèi)其他電腦命令行輸入:net time \\10.30.100.119 /set /yes,實(shí)現(xiàn)時(shí)間同步,其中10.30.100.119代表NTP服務(wù)器地址。
- C# Winform實(shí)現(xiàn)局域網(wǎng)時(shí)間同步demo:
全局變量:
//Timer System.Timers.Timer timer = new System.Timers.Timer(); //IP private string ipAddress; //時(shí)間間隔 private int timeInterval; //創(chuàng)建bat文件路徑,如果存在,直接覆蓋 private string filePath = System.Environment.CurrentDirectory + @"\timesync.bat";頁(yè)面Load方法:
private void FrmMain_Load(object sender,EventArgs e) {//運(yùn)行標(biāo)志隱藏picRun.Visible = false; }Run/Abort按鈕點(diǎn)擊事件:
private void btnRunAbort_Click(object sender,EventArgs e) {//IPipAddress = txtIP.Text.Trim();//Time IntervaltimeInterval = Convert.ToInt32(txtTimeInterval.Text);if (btnRunAbort.Text.Equals("開(kāi)始同步")){this.RunTimer();}else if (btnRunAbort.Text.Equals("停止同步")){//定時(shí)器停止 timer.Stop();timer = new System.Timers.Timer();MessageBox.Show("停止同步成功","提示");//運(yùn)行標(biāo)志隱藏picRun.Visible = false;btnRunAbort.Text = "開(kāi)始同步";} }開(kāi)始同步執(zhí)行方法:
public void RunTimer() {//創(chuàng)建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{//執(zhí)行時(shí)間超過(guò)10秒,強(qiáng)制結(jié)束if (!CallWithTimeOut(CommonRun,10000)){MessageBox.Show("服務(wù)器異常!","提示");return;}//服務(wù)器地址異常if (StringRun().EndsWith(@"/yes")){MessageBox.Show("服務(wù)器異常!","提示");return;}MessageBox.Show("開(kāi)始同步成功!","提示");//BeginInvokeSetPBState(true , "停止同步");}catch (Exception ex){MessageBox.Show("服務(wù)器異常!","提示");return;}//timer定時(shí)器執(zhí)行時(shí)間同步timer.Elapsed += new System.ElapsedEventHandle(TimerRun);timer.Enabled = true;timer.Interval = Convert.ToInt32(txtTimeInterval.Text) * 1000;timer.Start(); }?時(shí)間同步,返回執(zhí)行bat輸出:
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; }時(shí)間同步:
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定時(shí)器時(shí)間同步:
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:
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 = "停止同步";} }方法執(zhí)行時(shí)間超過(guò)設(shè)定值,強(qiáng)制結(jié)束:
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;} }- 運(yùn)行結(jié)果:
?
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/benpaodejiandan/p/8385448.html
總結(jié)
以上是生活随笔為你收集整理的C# Winform小程序:局域网设置NTP服务器、实现时间同步的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: AWS CSAA -- 04 AWS O
- 下一篇: 一个插件让你在 Redux 中写 pro