-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimeServer.java
More file actions
38 lines (35 loc) · 1.19 KB
/
TimeServer.java
File metadata and controls
38 lines (35 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// Time.java 8-3°ú ¿¬µ¿
import java.io.*;
import java.net.*;
import java.util.Date;
public class TimeServer {
public final static int PORT = 37;
public static void main(String[] args) {
// The time protocol sets the epoh at 1900,
// the Date class ant 1970. This number
// converts between them.
long differenceBetweenEpochs = 2208988800L;
try (ServerSocket server = new ServerSocket(PORT)) {
while (true) {
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;
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();
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
}catch (IOException ex) {
System.err.println(ex);
}
}
}