Reputation: 1195
i am having a very weird situation in my code which i dont understand i am sending an object lets say O through a socket then i am changing the value of a variable in the object and sending it again but the second time when i print it on the client side, i am getting the same values as in the 1st object.
client code:
while(true){
try{
order=(Order)ois.readObject();
System.out.println(order);
}
server code:
public void sendOrder(Order o){
try {
out.writeObject(o);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
main method:
Server_Socket ss=new Server_Socket();
ss.sendOrder(o);
o.add(r2);
ss.sendOrder(o);
The value is definitely changing on the serverside before i send it, but i dont understand why on the client side its not showing that r2 added in the object.
Upvotes: 1
Views: 173
Reputation: 310860
The objects are being cached by the ObjectOutputStream
. To prevent this, call ObjectOutputStream.reset()
after each write. If you are sending simple objects that don't contain other objects, use writeUnshared()
instead of writeObject()
.
Upvotes: 5
Reputation: 1388
The objects are being cached by the IOStreams. To fix this, create a deep clone on the server prior to sending the object back. When the client pulls the object from the stream, it will have a different instance id and it will actually deserialize and instantiate the object on the client side.
Fun stuff.
Upvotes: 0