I'm trying to send a serialized object from a client to server, where a server will read it as a byte array, create a memory stream with the byte array, and then deserialize using the memory stream.
It works properly the first time but when the first client disconnects and the second one connects and sends the object I get this:
Binary stream '0' does not contain a valid BinaryHeader.
or
No assembly ID for object type ''.
This is where the error is occurring:
private static async void HandleClient(TcpClient tcpClient)
{
NetworkStream networkStream;
try
{
networkStream = tcpClient.GetStream();
byte[] buff = new byte[1024];
while (true)
{
int recieved = await networkStream.ReadAsync(buff, 0, buff.Length);
if (recieved == 0)
{
Console.WriteLine("Client disconnected.");
break;
}
using (MemoryStream memoryStream = new MemoryStream(buff))
{
IFormatter formatter = new BinaryFormatter();
object obj = formatter.Deserialize(memoryStream);
if (obj is PersonData)
{
PersonData data = (PersonData)obj;
Console.WriteLine($"{data.name} - {data.age} - {data.gender}");
}
}
Array.Clear(buff, 0, buff.Length);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
Turns out the problem was in my client's code. I was serializing it directly to the network stream instead of just converting the object to an array of bytes and sending the array.