Java獲取網絡時間

轉載自 http://brokendreams.iteye.com/blog/1840603


獲取網絡時間有一個協議:Network Time Protocol(NTP: 網絡時間協議 )。 

        協議有了,那麼java有沒有相關實現呢。當然也有了。apache的commons-net包下面有ntp的實現。主要的類是: 
Java代碼  收藏代碼
  1. org.apache.commons.net.ntp.NTPUDPClient  

和 
Java代碼  收藏代碼
  1. org.apache.commons.net.ntp.TimeInfo  

看下用法,NTPUDPClient中有方法: 
Java代碼  收藏代碼
  1. public TimeInfo getTime(InetAddress host, int port) throws IOException  

和 
Java代碼  收藏代碼
  1. public TimeInfo getTime(InetAddress host) throws IOException  

第二個重載方法是用協議規範默認端口:123。 

看下具體實現代碼: 
Java代碼  收藏代碼
  1. /*** 
  2.      * Retrieves the time information from the specified server and port and 
  3.      * returns it. The time is the number of miliiseconds since 
  4.      * 00:00 (midnight) 1 January 1900 UTC, as specified by RFC 1305. 
  5.      * This method reads the raw NTP packet and constructs a <i>TimeInfo</i> 
  6.      * object that allows access to all the fields of the NTP message header. 
  7.      * <p> 
  8.      * @param host The address of the server. 
  9.      * @param port The port of the service. 
  10.      * @return The time value retrieved from the server. 
  11.      * @exception IOException If an error occurs while retrieving the time. 
  12.      ***/  
  13.     public TimeInfo getTime(InetAddress host, int port) throws IOException  
  14.     {  
  15.         // if not connected then open to next available UDP port  
  16.         if (!isOpen())  
  17.         {  
  18.             open();  
  19.         }  
  20.   
  21.         NtpV3Packet message = new NtpV3Impl();  
  22.         message.setMode(NtpV3Packet.MODE_CLIENT);  
  23.         message.setVersion(_version);  
  24.         DatagramPacket sendPacket = message.getDatagramPacket();  
  25.         sendPacket.setAddress(host);  
  26.         sendPacket.setPort(port);  
  27.   
  28.         NtpV3Packet recMessage = new NtpV3Impl();  
  29.         DatagramPacket receivePacket = recMessage.getDatagramPacket();  
  30.   
  31.         /* 
  32.          * Must minimize the time between getting the current time, 
  33.          * timestamping the packet, and sending it out which 
  34.          * introduces an error in the delay time. 
  35.          * No extraneous logging and initializations here !!! 
  36.          */  
  37.         TimeStamp now = TimeStamp.getCurrentTime();  
  38.   
  39.         // Note that if you do not set the transmit time field then originating time  
  40.         // in server response is all 0's which is "Thu Feb 07 01:28:16 EST 2036".  
  41.         message.setTransmitTime(now);  
  42.   
  43.         _socket_.send(sendPacket);  
  44.         _socket_.receive(receivePacket);  
  45.   
  46.         long returnTime = System.currentTimeMillis();  
  47.         // create TimeInfo message container but don't pre-compute the details yet  
  48.         TimeInfo info = new TimeInfo(recMessage, returnTime, false);  
  49.   
  50.         return info;  
  51.     }  

       大概過程就是想目標網絡地址發包來獲取網絡時間,具體細節由協議來規範。 
所以我們還需要來確定網絡地址,繼續搜索,發現網絡上有時間服務器,也叫授時服務器。我們的用智能手機的時間是不是通過這種方式來同步的呢? 
       找到了這樣一些服務器地址: 
中國時間網 
       國外的 
NIST Internet Time Servers 

代碼例子: 
Java代碼  收藏代碼
  1. public static void main(String[] args) {  
  2.     try {  
  3.         NTPUDPClient timeClient = new NTPUDPClient();  
  4.         String timeServerUrl = "time-a.nist.gov";  
  5.         InetAddress timeServerAddress = InetAddress.getByName(timeServerUrl);  
  6.         TimeInfo timeInfo = timeClient.getTime(timeServerAddress);  
  7.         TimeStamp timeStamp = timeInfo.getMessage().getTransmitTimeStamp();  
  8.         DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");  
  9.         System.out.println(dateFormat.format(timeStamp.getDate()));  
  10.     } catch (UnknownHostException e) {  
  11.         e.printStackTrace();  
  12.     } catch (IOException e) {  
  13.         e.printStackTrace();  
  14.     }  
  15. }  


輸出:
Java代碼  收藏代碼
  1. 2013-04-02 11:01:08  


可調整本機時間,然後觀察輸出是否正確。
發佈了26 篇原創文章 · 獲贊 82 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章