Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 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 Reply

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...