java ntp client_Java NTP 客户端协议实现

importjava.io.InputStream;importjava.net.Socket;/***

*@authorray (justinlei@gmail.com)

* @date 2009-8-27

*@version1.0*/publicclassTimeUtil {publicstaticfinalintDEFAULT_PORT=37;publicstaticfinalString DEFAULT_HOST="time-nw.nist.gov";privateTimeUtil() {

};publicstaticlongcurrentTimeMillis(Boolean sync) {if(sync!=null&&sync.booleanValue()!=true)returnSystem.currentTimeMillis();try{returnsyncCurrentTime();

}catch(Exception e) {returnSystem.currentTimeMillis();

}

}publicstaticlongsyncCurrentTime()throwsException {//The time protocol sets the epoch at 1900,//the java Date class at 1970. This number//converts between them.longdifferenceBetweenEpochs=2208988800L;//If you'd rather not use the magic number uncomment//the following section which calculates it directly./** TimeZone gmt = TimeZone.getTimeZone("GMT"); Calendar epoch1900 =

* Calendar.getInstance(gmt); epoch1900.set(1900, 01, 01, 00, 00, 00);

* long epoch1900ms = epoch1900.getTime().getTime(); Calendar epoch1970

* = Calendar.getInstance(gmt); epoch1970.set(1970, 01, 01, 00, 00, 00);

* long epoch1970ms = epoch1970.getTime().getTime();

*

* long differenceInMS = epoch1970ms - epoch1900ms; long

* differenceBetweenEpochs = differenceInMS/1000;*/InputStream raw=null;try{

Socket theSocket=newSocket(DEFAULT_HOST, DEFAULT_PORT);

raw=theSocket.getInputStream();longsecondsSince1900=0;for(inti=0; i<4; i++) {

secondsSince1900=(secondsSince1900<<8)|raw.read();

}if(raw!=null)

raw.close();longsecondsSince1970=secondsSince1900-differenceBetweenEpochs;longmsSince1970=secondsSince1970*1000;returnmsSince1970;

}catch(Exception e) {thrownewException(e);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值