?? 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 + -