1 package org.apache.commons.net.time;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 import java.io.DataOutputStream;
21 import java.io.IOException;
22 import java.net.ServerSocket;
23 import java.net.Socket;
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41 public class TimeTestSimpleServer implements Runnable
42 {
43
44
45
46
47 public static final long SECONDS_1900_TO_1970 = 2208988800L;
48
49
50 public static final int DEFAULT_PORT = 37;
51
52 private ServerSocket server;
53 private final int port;
54 private boolean running = false;
55
56
57
58
59
60 public TimeTestSimpleServer()
61 {
62 port = DEFAULT_PORT;
63 }
64
65
66
67
68 public TimeTestSimpleServer(int port)
69 {
70 this.port = port;
71 }
72
73 public void connect() throws IOException
74 {
75 if (server == null)
76 {
77 server = new ServerSocket(port);
78 }
79 }
80
81 public int getPort()
82 {
83 return server == null ? port : server.getLocalPort();
84 }
85
86 public boolean isRunning()
87 {
88 return running;
89 }
90
91
92
93
94
95 public void start() throws IOException
96 {
97 if (server == null)
98 {
99 connect();
100 }
101 if (!running)
102 {
103 running = true;
104 new Thread(this).start();
105 }
106 }
107
108
109 public void run()
110 {
111 Socket socket = null;
112 while (running)
113 {
114 try
115 {
116 socket = server.accept();
117 DataOutputStream os = new DataOutputStream(socket.getOutputStream());
118
119 int time = (int) ((System.currentTimeMillis() + 500) / 1000 + SECONDS_1900_TO_1970);
120 os.writeInt(time);
121 os.flush();
122 } catch (IOException e)
123 {
124 } finally
125 {
126 if (socket != null) {
127 try
128 {
129 socket.close();
130 } catch (IOException e)
131 {
132 System.err.println("close socket error: " + e);
133 }
134 }
135 }
136 }
137 }
138
139
140
141
142 public void stop()
143 {
144 running = false;
145 if (server != null)
146 {
147 try
148 {
149 server.close();
150 } catch (IOException e)
151 {
152 System.err.println("close socket error: " + e);
153 }
154 server = null;
155 }
156 }
157
158 public static void main(String[] args)
159 {
160 TimeTestSimpleServer server = new TimeTestSimpleServer();
161 try
162 {
163 server.start();
164 } catch (IOException e)
165 {
166 }
167 }
168
169 }