1

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

Taifunov
  • 533
  • 1
  • 4
  • 9

1 Answers1

0

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)
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900