服务端
程序入口
package w1;
public class RunServer {
public static void main(String[] args) {
// TODO Auto-generated method stub
Study2Server study2Server = new Study2Server();
study2Server.start();
}
}
程序主体
package w1;
import java.util.Calendar;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.net.*;
public class Study2Server extends Thread{
public static int num=0;
private int year;
private int month;
private int day;
private int hour;
private int minute;
private int s;
private static ServerSocket socket = null;
public Study2Server() {
super();
if(socket==null) {
try {
socket = new ServerSocket(4700);
}catch(Exception e) {
e.printStackTrace();
}
}
}
// public static void main(String[] args) {
// // TODO Auto-generated method stub
// Study2Server study2Server = new Study2Server();
// Thread thread=new Thread(study2Server,num+"");
// thread.start();
//
// }
public static void print(String s) {
System.out.println(s);
}
public void run() {
try {
Socket sc = socket.accept();
num++;
print(num+"succed");
OutputStreamWriter ow = new OutputStreamWriter(sc.getOutputStream());
BufferedWriter bw = new BufferedWriter(ow);
Calendar calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH)+1;
day = calendar.get(Calendar.DAY_OF_MONTH);
hour = calendar.get(Calendar.HOUR);
minute = calendar.get(Calendar.MINUTE);
s = calendar.get(Calendar.SECOND);
String ss = year+":"+month+":"+day+":"+hour+":"+minute+":"+s;
bw.write(ss);
bw.close();
sc.close();
}catch(Exception e) {
try {
new Thread().sleep(10);
}catch(Exception ee) {
ee.printStackTrace();
}
}finally {
try {
Study2Server study2Server = new Study2Server();
study2Server.start();
}catch(Exception e) {
e.printStackTrace();
}
}
}
}
客户端
package w1;
import java.net.;
import java.io.;
public class GetTime {
//time.nist.gov
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Socket sc = new Socket(InetAddress.getByName("localhost"),4700);
//Socket sc = new Socket(InetAddress.getByName("time.nist.gov"),13);//如果是下面这个就是获取公网上的时间 上面哪个是自己创建的服务器来获取时间
InputStreamReader ir = new InputStreamReader(sc.getInputStream());
BufferedReader br = new BufferedReader(ir);
String s;
while((s=br.readLine())!=null) {
if(s.length()>1){
String[] ss = s.split(" ");
if(ss.length>1) { //这里是对公网上获取的时间的处理 以便显示正确好看的时间形式
//print(ss[1]+" "+ss[2]);
String[] sss = ss[2].split(":");
int h = Integer.parseInt(sss[0]);
h = h+8;
sss[0] = String.valueOf(h);
print(ss[1]+" "+sss[0]+":"+sss[1]+":"+sss[2]);
}else {//如果自己的服务器就是直接获取一行字符串
print(ss[0]);
}
}
}
}catch(Exception e) {
e.printStackTrace();
}
}
public static void print(String s) {
System.out.println(s);
}
}