Reputation: 2465
Im trying to send an object back and forth between a client and server and when it leaves the client, all the data is there, i.e z = 6.0 but when it reaches the server, all the data is reset, i.e z = 0.0
I though it might of had something to do with me initializing variable in the object so I don't initialize anything, I also have added a constructor but nothing seems to work.
Object:
public class PlayerData implements Serializable{
String name;
int id;
double x,y,z;
double rotation;
PlayerData(String name, double x, double y, double z) {
this.name = name;
this.x = x;
this.y = y;
this.z = z;
id = -1;
}
}
Client Sending:
Thread t = new Thread(){
public void run() {
while(true){
try{
System.out.println("Client writing player z: " + player.z);
streamOut.writeObject(player);
streamOut.flush();
}catch(Exception ioe){
System.out.println("Sending Error: "+ ioe.getMessage());
}
}
}
};
t.start();
Server:
boolean done = false;
while(!done) {
//if(streamIn.available() > 0)
try {
Object o = streamIn.readObject();
if(o instanceof PlayerData){
PlayerData recieved = (PlayerData) o;
System.out.println("S: obj recieved z " + recieved.z);
for(int i = 0; i < serv.clientOut.size(); i++) {
serv.clientOut.get(i).writeObject(recieved);
serv.clientOut.get(i).flush();
}
}else
System.out.println("Server: bad object");
}
catch(IOException e) {
done = true;
}
}
And it will say
Client writing player z: -42.05979919433594
S: obj recieved z 0.0
Upvotes: 0
Views: 600
Reputation: 1499780
You're repeated sending the same object via serialization - and ObjectOutputStream
notices that, and instead resolves this to references to the same object.
If you want to effectively send a separate object on each call, add this to your loop:
streamOut.reset();
That way, every time you write the object, it will write it out as if it's never seen it before (and you'll get a new object on each readObject
call on the other side). Of course, that means the stream will be a lot bigger. Personally I'd consider using an alternative serialization technique such as Protocol Buffers, but that's a different matter...
Upvotes: 1