📄 usetimeserver.java
字号:
import java.net.*;import java.io.*;import java.util.Date; public class useTimeServer { //设置常数属性 public final static int DEFAULT_PORT = 37; //主程序 public static void main(String[] args) { //设置缺省端口 int port = DEFAULT_PORT; if (args.length > 0) { try { //从参数中获取端口信息 port = Integer.parseInt(args[0]); //判断端口输入是否正确 if (port < 0 || port >= 65536) { System.out.println("Port must between 0 and 65535"); return; } } //捕获异常 catch (NumberFormatException e) {} } // 时间协议设置从1900年开始纪年 //java Date类从1970年开始纪年 // 在当中要进行数量转换 //设置转换常量 long differenceBetweenEpochs = 2208988800L; try { //建立ServerSocket ServerSocket server = new ServerSocket(port); //服务一直运行 while (true) { Socket connection = null; try { //建立Socket连接 connection = server.accept(); //建立输出流对象 OutputStream out = connection.getOutputStream(); //新建时间对象 Date now = new Date(); //获取时间 long msSince1970 = now.getTime(); long secondsSince1970 = msSince1970/1000; //处理纪年差异 long secondsSince1900 = secondsSince1970+ differenceBetweenEpochs; //获取符合Time协议的时间值 byte[] time = new byte[4]; time[0]= (byte) ((secondsSince1900 & 0x00000000FF000000L) >> 24); time[1]= (byte) ((secondsSince1900 & 0x0000000000FF0000L) >> 16); time[2]= (byte) ((secondsSince1900 & 0x000000000000FF00L) >> 8); time[3] = (byte) (secondsSince1900 & 0x00000000000000FFL); //输出时间值 out.write(time); out.flush(); } // end try catch (IOException e) {} // end catch finally { //关闭连接 if (connection != null) connection.close(); } } // end while } // end try catch (IOException e) { System.err.println(e); } // end catch } // end main} // end useTimeServer
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -