Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

serialization - .NET The input stream is not a valid binary format tcp

Please tell where i can have problem in my code?

I serialize the data into a list of objects, then send it to the tcp server for further manipulations This is how serialization works:

var objList = new List<object>
{
  path,
  attachmentContext.LogItemInfo.Attachment
};

byte[] toServer;
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
      bf.Serialize(ms, objList);
      toServer = ms.ToArray();
}

_client.SendAsync(toServer);

So some transmissions are serialized successfully, then somewhere on the random it fails enter image description here

question from:https://stackoverflow.com/questions/65885722/net-the-input-stream-is-not-a-valid-binary-format-tcp

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I strongly suspect that the problem here is "framing", meaning: the buffer that you're processing does not contain exactly one message. It could contain the start of a message, or an entire message and part of the next, either of which can cause problems. TCP is a stream, not a series of messages. The good news is that BinaryFormatter has framing built in anyway, so honestly: you could just use the NetworkStream directly and it should just work. Otherwise, you're going to need to implement your own framing layout, and make sure that the receiving code reads an entire frame before processing data and deals correctly with any over-read, i.e. it should retain any bytes that belong to the next frame.

The bad news is that you should not ever use BinaryFormatter, and in particular you shouldn't use it in a socket server (where the client should always be considered hostile). Further reading.

To investigate whether framing is the problem:

  • at the client, log the hex of each message that you're sending
  • at the client, log the hex of each message that you're trying to process
  • now compare them; they should match message-to-message ("starting the same" isn't enough; they need to be the same length, and identical throughout)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...