Hello!
My code is misbehaving and I can't see where the fault is, but I'm almost sure that it's a beginner's mistake. I'm sending objects through a socket in a while loop. The object has 4 fields: first three are double[] arrays and the last one is a Timestamp. The objects are being received also in a loop.
On the server side, before sending the object I print its fields and they are ok (the data in the object's fields changes at each iteration) but when I receive the object on the client side it has the same values in the three double[] fields as the first object that was sent (the first object was correctly received). The strange thing is that the Timestamp field is correct for all the received objects.
Here's the relevant code:
public class Server extends Thread{ ServerSocket ss=null; Socket socket=null; String line=""; Measurements mes = new Measurements(); public void run(){ try{ ss = new ServerSocket(1905); socket = ss.accept(); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); ObjectOutputStream out = new ObjectOutputStream((socket.getOutputStream())); double x[] = new double[6]; double u[] = new double[6]; double v[] = new double[6]; line = in.readLine(); while ((!line.equals("STOP")) && (line.equals("Get Measurements"))){ for (int i=0;i<6;i++){ synchronized (Simulator.lakes[i]){ v[i]=Simulator.lakes[i].getInFlow(); u[i]=Simulator.lakes[i].getOutFlow(); x[i]=Simulator.lakes[i].getLevel();} } mes=new Measurements(); mes.setX(x); mes.setU(u); mes.setV(v); Calendar calendar = Calendar.getInstance(); java.util.Date now = calendar.getTime(); java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime()); mes.setDate(currentTimestamp); System.out.println("In server: x[1]="+ mes.getX()[1]+" u[1]="+mes.getU()[1]+" v[1]="+mes.getV()[1]+"date= "+mes.getDate()); out.writeObject(mes); sleep(1000); out.flush(); line = in.readLine(); } }catch(Exception e){e.printStackTrace();} } }
In the client class:
public Measurements getMeasurements(){ out.println("Get Measurements"); try { m=(Measurements) in.readObject(); System.out.println("In client: x[1]="+ m.getX()[1]+" u[1]="+m.getU()[1]+" v[1]="+m.getV()[1]+" date= "+m.getDate()); } catch (Exception e) { e.printStackTrace(); } return m; }
The output is:
In server: x[1]=77.3336 u[1]=0.7897 v[1]=0.5128 date= 2010-11-15 08:26:57.681
In server: x[1]=32.5530 u[1]=0.6430 v[1]=0.9706 date= 2010-11-15 08:26:58.768
In server: x[1]=46.0680 u[1]=0.3521 v[1]=0.7266 date= 2010-11-15 08:26:59.774
In server: x[1]=49.1065 u[1]=0.1337 v[1]=0.3319 date= 2010-11-15 08:27:00.775
...
In client: x[1]=77.3336 u[1]=0.7897 v[1]=0.5128 date= 2010-11-15 08:26:57.681
In client: x[1]=77.3336 u[1]=0.7897 v[1]=0.5128 date= 2010-11-15 08:26:58.768
In client: x[1]=77.3336 u[1]=0.7897 v[1]=0.5128 date= 2010-11-15 08:26:59.774
In client: x[1]=77.3336 u[1]=0.7897 v[1]=0.5128 date= 2010-11-15 08:27:00.775
...
Any ideas why this is happening?
Thanks,
Alexandra