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 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 public void run()
109 {
110 Socket socket = null;
111 while (running)
112 {
113 try
114 {
115 socket = server.accept();
116 DataOutputStream os = new DataOutputStream(socket.getOutputStream());
117
118 int time = (int) ((System.currentTimeMillis() + 500) / 1000 + SECONDS_1900_TO_1970);
119 os.writeInt(time);
120 os.flush();
121 } catch (IOException e)
122 {
123 } finally
124 {
125 if (socket != null)
126 try
127 {
128 socket.close();
129 } catch (IOException e)
130 {
131 System.err.println("close socket error: " + e);
132 }
133 }
134 }
135 }
136
137
138
139
140 public void stop()
141 {
142 running = false;
143 if (server != null)
144 {
145 try
146 {
147 server.close();
148 } catch (IOException e)
149 {
150 System.err.println("close socket error: " + e);
151 }
152 server = null;
153 }
154 }
155
156 public static void main(String[] args)
157 {
158 TimeTestSimpleServer server = new TimeTestSimpleServer();
159 try
160 {
161 server.start();
162 } catch (IOException e)
163 {
164 }
165 }
166
167 }