Java实现Socket之TimeClient
代码内容
代码实现
import java.io.*;
import java.net.*;
import java.util.Date;
public class TimeClient {
public final static long differenceBetweenEpochs = 2208988800L;
public static void main(String[] args) {
try {
InetAddress host = InetAddress.getByName("time.nist.gov");
int port = 37;
if (args.length > 0) {
host = InetAddress.getByName(args[0]);
}
Socket s = new Socket(host, port);
InputStream raw = s.getInputStream();
long secondsSince1900 = 0;
for (int i = 0; i < 4; i++) {
secondsSince1900 = (secondsSince1900 << 8) | raw.read();
}
long secondsSince1970 = secondsSince1900 - differenceBetweenEpochs;
long msSince1970 = secondsSince1970 * 1000;
Date time = new Date(msSince1970);
System.out.println("It is " + time);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行截图
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步