本文主要是介绍如何进行网络对时,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
注意添加头文件
#include <iostream>
#include <vector>
using namespace std;
#include<math.h>
//时间同步
CSocket sockClient;
TIME_ZONE_INFORMATION tzinfo;DWORD dwStandardDaylight;
long bias,sminute,shour;
vector <string> vi;
string strServer;
BOOL ret;
//将时间服务器放在一个VECTOR中。
strServer = "time.nist.gov";
vi.push_back(strServer);
strServer = "time-a.nist.gov";
vi.push_back(strServer);
strServer = "time-b.nist.gov";
vi.push_back(strServer);
strServer = "time-nw.nist.gov";
vi.push_back(strServer);
strServer = "nist1.nyc.certifiedtime.com";
vi.push_back(strServer);
strServer = "time-b.nist.gov";
vi.push_back(strServer);
//初始化CSocket
AfxSocketInit();
sockClient.Create(); //创建socket
UpdateData(FALSE);
dwStandardDaylight = GetTimeZoneInformation(&tzinfo); //获取时区与UTC的时间差 应该返回-8
bias = tzinfo.Bias;
if (dwStandardDaylight == TIME_ZONE_ID_INVALID) //函数执行失败
{
return;
}
if (dwStandardDaylight == TIME_ZONE_ID_STANDARD) //标准时间有效
bias += tzinfo.StandardBias;
if (dwStandardDaylight == TIME_ZONE_ID_DAYLIGHT) //夏令时间
bias += tzinfo.DaylightBias;
shour = bias/60;
sminute = fmod(bias,60);
/*
原型:extern float fmod(float x, float y);
用法:#include <math.h> 功能:计算x/y的余数 说明:返回x-n*y,符号同y。n=[x/y](向离开零的方向取整)
*/
//循环判断服务器是否连接成功
for (int n=0; n < vi.size(); ++ n)
{
ret = sockClient.Connect(vi[n].c_str(),13);
if (1 == ret)
break;
}
unsigned char nTime[40]; //临时接收数据要求足够的大
memset(nTime, 0, sizeof(nTime));
sockClient.Receive(nTime, sizeof(nTime)); //接收服务器发送来得的数据
sockClient.Close(); //关闭socket
CString strTime;
strTime.Format("%s",nTime);
int first=strTime.Find("-");
int second=strTime.Find("-",first+1);
int tfirst = strTime.Find(":");
int tsecond = strTime.Find(":",tfirst+1);
int hyear=2000+atoi(strTime.Mid(first-2,2));
int hmonth=atoi(strTime.Mid(first+1,2));
int hday=atoi(strTime.Mid(second+1,2));
int hhour=atoi(strTime.Mid(tfirst-2,2))-shour;
int hminute=atoi(strTime.Mid(tfirst+1,2))-sminute;
int hsecond=atoi(strTime.Mid(tsecond+1,2));
CTime temptime(hyear,hmonth,hday,hhour,hminute,hsecond);
//设置系统时间
SYSTEMTIME systm;
systm.wYear = temptime.GetYear();
systm.wMonth = temptime.GetMonth();
systm.wDay = temptime.GetDay();
systm.wHour = temptime.GetHour();
systm.wMinute = temptime.GetMinute();
systm.wSecond = temptime.GetSecond();
systm.wMilliseconds = 0;
if(0 != ::SetLocalTime(&systm))
{
UpdateData(FALSE);
AfxMessageBox("本地时间设置成功!!!");
}
else
{
UpdateData(FALSE);
AfxMessageBox("本地时间设置失败!!!");
}
这篇关于如何进行网络对时的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!