嗨,我在将 Date 对象从客户端发送到服务器时遇到了一点麻烦,以便我可以比较它们。所以基本上我要做的是:1)发送日期对象2)比较他们的时间3)将时间设置为两台机器的平均时间
到目前为止,我已经这样做了:
服务器:
public class Server implements Runnable{
private int port;
private String name;
private Date mydate = new Date();
private Date date;
public Server(int port, String name){
this.port=port;
this.name=name;
}
public synchronized void run(){
while(true){
try{
method();
}
catch(Exception e){
return;
}
}
}
public synchronized void method() throws Exception{
long dates;
long average=0;
String[] values = new String[10];
DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss zzz yyyy");
ServerSocket server = new ServerSocket(port);
Socket s=server.accept();
InputStream in= s.getInputStream();
OutputStream out = s.getOutputStream();
PrintWriter w = new PrintWriter(out);
Scanner r = new Scanner(in);
for(int i=0; i<10; i++){
String msg = r.next();
values[i] = msg;
}
for(int j=0; j<values.length; j++){
dates = Long.parseLong(values[j]);
date = new Date(dates);
average = average + date.getTime();
}
average = (average - mydate.getTime())/2;
mydate.setTime(average);
System.out.println(name+": "+mydate.toString());
}
}
客户:
public class Client implements Runnable{
private int port;
private int id;
Date time = new Date();
Date time2 = new Date();
public Client(int port,int id){
this.port=port;
this.id = id;
}
public synchronized void run(){
try{
Thread.sleep(5000);
method();
}
catch(Exception e){
return;
}
}
public synchronized void method() throws Exception{
DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss zzz yyyy");
Random ran = new Random(500);
int d = ran.nextInt(500)+500;
time.setTime(time.getTime()+d);
String datestr;
Socket s = new Socket("localhost", port);
InputStream in= s.getInputStream();
OutputStream out = s.getOutputStream();
PrintWriter w = new PrintWriter(out);
Scanner r = new Scanner(in);
for(int i=0; i<10; i++){
time.setTime(time.getTime()+d);
datestr = df.format(time);
w.println(datestr);
w.flush();
}
}
}
但我得到的结果是“没有”只是空白。该程序编译得很好,现在出现错误,我有点知道问题出在哪里,但我只是不知道如何正确解析这些值,以便正确读取它们。请帮助我:S