java - Socket transferring -
i have several classes running @ same time input server. both have sockets set up.
the problem that, though transfer same data between classes, when data arrives, not same.
here sending method:
private boolean transferbroadcastdata() { boolean success = false; try { vector<client> clientslist = onlinelist.getclientslist(); (client client : clientslist) { objectoutputstream objectoutputstream = client.getobjectoutputstream(); objectoutputstream.writeobject(clientslist); objectoutputstream.flush(); } success = true; } catch (exception ioexception) { ioexception.printstacktrace(); } return success; }
and here receiving-method:
while (true) { try { object object = objectinputstream.readobject(); if (object instanceof vector<?>) { string x = "i got it:\n"; vector<client> clients = (vector<client>) object; for(client c : clients) { x += "\n" + c; } joptionpane.showmessagedialog(clientmanager.this, x); userspanel.addclientstolist((vector<client>) object); } else if (object instanceof message) messagepanel.appendtext((message) object); } catch (classnotfoundexception classnotfoundexception) { statuspanel.updatestatus("error reading socket"); } }
when receive vector on clients, elements in different. not content of vector tried transfer.
what missing?
the problem use of serialization / objectoutputstream. when object serialized objectoutputstream keeps internal records "optimize" serialization process, if serialize same object twice repeats id , assumes object hasnt changed. example if run code:
objectoutputstream oos = new objectoutputstream(); myobject[] arr = new myobject[]{myobject}; oos.write(myobject); oos.write(arr);
the output might (note not actual format example):
[[myobject;id=357;foo=bar;baz=36;]] [[myobject[];id=358;data={id=357}]]
note array not serialize object again, rather id serialized version. taking 1 step further if have code:
objectoutputstream oos = new objectoutputstream(); oos.write(myobject); myobject.setbaz(99999); oos.write(myobject);
you'll end with:
[[myobject;id=357;foo=bar;baz=36;]] {id=357}
note even though object changed internal id serialized. trick when writing objects need clear internal state of objectoutputstream, can accomplished reset(). javadocs:
reset disregard state of objects written stream. state reset same new objectoutputstream.
so if take previous example , add reset:
objectoutputstream oos = new objectoutputstream(); oos.write(myobject); myobject.setbaz(99999); oos.reset(); oos.write(myobject);
you should output expected behaviour of:
[[myobject;id=357;foo=bar;baz=36;]] [[myobject;id=358;foo=bar;baz=99999;]]
one things careful of note second serialization will considered different object original serialization. depending on how transferring data , internal relationship must careful not reset stream if objects share references 1 , want relationships maintained.
Comments
Post a Comment