简体   繁体   中英

Serialization of Frequently Changing List

I have a server application and a client application, and a List (an ArrayList to be specific) exists at the server. The client sends the server some information, the server modifies parts of the List , and sends it to the client by serializing it over the network.

The first time this is done, the client receives the List (or is it a copy of/reference to the original?), but after that, the client's List never changes though the server sends a modified version. The server is surely modifying the List because watching it in a debugger clearly shows the modifications.

The client-side code is like

List<Type> fromServer = new ArrayList<>();
...
// send information
...
fromServer = (List<Type>) in.readObject();

and the server-side like

List<Type> toClient = new ArrayList<>();
...
// get information from client
// add/modify list elements
...
out.writeObject(toClient);

where in and out are input/output streams over sockets.

Why does this happen and what can I do to fix this problem? Is it occuring because the List is assumed to be unchanged? Thanks for your attention!

每当需要序列化同一对象的新版本时,都需要使用ObjectOutputStream.reset()

I would recommend that you stop using the built in object serialization. It has severe drawbacks:

  • It uses a binary format that is difficult to debug
  • It is version dependent: both your client and server will need to be running the same version of Java
  • Changes to your data structures will likely lead to incompatibilities between your client and server

Instead, I recommend using JSON serialization using a library like Google Gson or json-io . It is much easier to expect the data on the wire (or in the debugger) and make sure that that data you are receiving is what you expect. It will also allow you to be forward and backward compatible, both with different versions of Java and your own data structures.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM