整理代码,发现某个加班的夜晚帮忙写的一段代码,为了验证一个时间延迟的bug:
package com.isoft.test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestGetTime {
private static SimpleDateFormat sdf = null;
private static String serverTime = null;
private static boolean isRun = true;
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("===========================================");
TestGetTime test = new TestGetTime();
test.printThread.start();
}
Thread printThread = new Thread(){
@Override
public void run() {
while(isRun){
try {
Thread.sleep(1000);
printClientTime();
pinrtServerTime();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
private static void printClientTime(){
Date cDate = new Date();
System.out.println("Client Time="+sdf.format(cDate));
}
private static long pinrtServerTime() {
long time = 0;
String urls = "http://192.168.60.99/test.php";
try {
URL url = new URL(urls);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.connect();
InputStream is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
int index=0;
while ((line = br.readLine()) != null) {
serverTime = line;
System.err.println("Server Time="+serverTime);
Date sDate,cDate;
try {
sDate = sdf.parse(serverTime);
cDate = new Date();
long interval = (sDate.getTime()-cDate.getTime())/1000;
System.err.println("sDate-cDate="+interval+"秒");
if(Math.abs(interval)>=65){
isRun = false;
System.err.println("偶偶,出现异常了");
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
con.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return time;
}
}