1 package org.apache.commons.net.time; 2 3 57 58 import java.io.DataOutputStream ; 59 import java.io.IOException ; 60 import java.net.ServerSocket ; 61 import java.net.Socket ; 62 63 79 public class TimeTestSimpleServer implements Runnable 80 { 81 82 85 public static final long SECONDS_1900_TO_1970 = 2208988800L; 86 87 88 public static final int DEFAULT_PORT = 37; 89 90 private ServerSocket server; 91 private int port; 92 private boolean running = false; 93 94 98 public TimeTestSimpleServer() 99 { 100 port = DEFAULT_PORT; 101 } 102 103 106 public TimeTestSimpleServer(int port) 107 { 108 this.port = port; 109 } 110 111 public void connect() throws IOException 112 { 113 if (server == null) 114 { 115 server = new ServerSocket (port); 116 } 117 } 118 119 public int getPort() 120 { 121 return server == null ? port : server.getLocalPort(); 122 } 123 124 public boolean isRunning() 125 { 126 return running; 127 } 128 129 133 public void start() throws IOException 134 { 135 if (server == null) 136 { 137 connect(); 138 } 139 if (!running) 140 { 141 running = true; 142 new Thread (this).start(); 143 } 144 } 145 146 public void run() 147 { 148 Socket socket = null; 149 while (running) 150 { 151 try 152 { 153 socket = server.accept(); 154 DataOutputStream os = new DataOutputStream (socket.getOutputStream()); 155 int time = (int) ((System.currentTimeMillis() + 500) / 1000 + SECONDS_1900_TO_1970); 157 os.writeInt(time); 158 os.flush(); 159 } catch (IOException e) 160 { 161 } finally 162 { 163 if (socket != null) 164 try 165 { 166 socket.close(); } catch (IOException e) 168 { 169 System.err.println("close socket error: " + e); 170 } 171 } 172 } 173 } 174 175 178 public void stop() 179 { 180 running = false; 181 if (server != null) 182 { 183 try 184 { 185 server.close(); } catch (IOException e) 187 { 188 System.err.println("close socket error: " + e); 189 } 190 server = null; 191 } 192 } 193 194 public static void main(String [] args) 195 { 196 TimeTestSimpleServer server = new TimeTestSimpleServer(); 197 try 198 { 199 server.start(); 200 } catch (IOException e) 201 { 202 } 203 } 204 205 } 206 | Popular Tags |