Yesterday when I was doing database synchronization testing, I used a bit of serialization and deserialization technology. I abstract the fields of a table into an entity class DiagramInfo, then store the new records of the client in a generic collection, and then serialize this generic collection and send it to the server through TCP, which deserializes it, and then writes this data to the database. This is probably the process of this operation.
Serialization I use the System.Runtime.Serialization.Iformatter class to serialize generic collections into binary streams. Some of the serialized code is as follows:
- private void Seriable(List diagrams)
- {
- MemoryStream stream = new MemoryStream();
- IFormatter formater = new BinaryFormatter();
- formater.Serialize(stream, diagrams);
- stream.Flush();
- serializedData = stream.ToArray();
- stream.Close();
- }
Copy code Then send using the TCP protocol, this part is omitted.
The server partially receives the data, saves it as a MemoryStream, and then deserializes it, part of the code is as follows:
- do
- {
- bytesRead = stream.Read(responseBuffer, 0, bufferSize);
- memstream.Write(responseBuffer, 0, bytesRead);
- }
- while (bytesRead > 0);
- IFormatter formater = new BinaryFormatter();
- diagrams = (List)formater.Deserialize(memstream);
- stream.Close();
- memstream.Close();
- client.Close();
Copy codeAt this time, run the client and server to synchronize the data, and the following error message appears: Error behavior: diagrams = (List)formater. Deserialize(memstream); Literally: encountered the end of the stream before the conversion was complete. 2. SolutionAfter a Google search, someone answered the following error possibilities:1. The types of serialization and deserialization are different, which can be excluded here; 2. There is no buffer to clear the stream during serialization, and the Flush() method is not used, which can also be excluded here. 3. The buffer size of the receiving process before deserialization may not be enough, I think there should be no problem with this, deserialization is carried out after the acquisition stream, it should have nothing to do with the size of the buffer, personal opinion, I have not tried it; 4. Add before deserializationstrem. Position=0。 (Stream is the stream to be deserialized, actually memstream) After testing, the fourth may work for my program. So why is this happening, after a single step of debugging, observe the memstream. Postion's value changes, and it is found that every time a write operation is performed, the value points to the end, which explains why the program reports such an error. But what I don't understand is why the deserialization function (Deserialize) instead of deserializing the entire stream by default, starting from where the Positon is?
|