Data inconsistency between the two ends of the object stream: data inconsistency between the two ends of the stream
Data inconsistency between the two ends of the object stream:Status when sending and receiving data for the server: There are two objects in the players list, but there is only one object when receiving data from the client. After multiple tests, it is found that there is a problem with only the class GameMessage at a time. Therefore, multiple possibilities are excluded, and the final confirmation is the problem of serialization.The reason is as follows:The GameMessage class contains a reference to the players ArrayList object. This reference is assigned when a constructor with parameters is called. The following constructor:
public GameMessage(ArrayList<Player> players, Point food){ super(); //this.players = players; //this.players.addAll(players); for(Player player : players) { this.players.add(new Player(player)); } //this.food = food; this.food = new Point(food);}
Before modification, the reference in this class is directed to the original object in the heap, so there is only one unique object in the heap. When the object stream is serialized for multiple times, it will be considered that the same object is being serialized, so that it will not be serialized multiple times. Instead, it will only output the number at the first serialization, then, the players list sent for the first time can be deserialized at each receiving time!
After the modification, a new object is created for each value assignment, and the JVM reserializes the players list for each serialization. The output data is normal.
The principle is as follows: (java crazy Handout)
Status when the server sends data (two players are in the players list at this time ):
At this time, the client is waiting (stuck in the read Statement ):
The status when the client receives the data (the players list now has only one player ):