用Java实现的一个简单的NTP客户端:
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import org.apache.commons.net.ntp.NTPUDPClient;
import org.apache.commons.net.ntp.TimeInfo;
import org.apache.commons.net.ntp.TimeStamp;
public class NTPClient {
public static void main(String[] args) {
try {
NTPUDPClient timeClient = new NTPUDPClient();
String timeServerUrl = "130.149.17.21";
InetAddress timeServerAddress = InetAddress.getByName(timeServerUrl);
TimeInfo timeInfo = timeClient.getTime(timeServerAddress);
TimeStamp timeStamp = timeInfo.getMessage().getTransmitTimeStamp();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
System.out.println("时间:" + dateFormat.format(timeStamp.getDate()));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/184147.html原文链接:https://javaforall.cn