I am trying to send a serialized object through a network tunnel, and while sending it, it adds whitespace (blank) at the end of the byte[], so it fits the selected size. When I go to deserialize it, it throws an error:
SerializationException: End of Stream encountered before parsing was completed
Code:
[Serializable]
class Foo
{
public int number;
public string str;
}
public class ExampleServer
{
public static void Main(string[] args)
{
TcpListener listener = new TcpListener(9000);
listener.Start();
TcpClient serverClient = listener.AcceptTcpClient();
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
byte[] buffer = new byte[2048];
serverClient.GetStream().Read(buffer, 0, buffer.Length);
stream.Write(buffer, 0, buffer.Length);
Foo fo = (Foo)formatter.Deserialize(stream);
Console.WriteLine(fo.number);
}
}
public class ExampleClient
{
public static void Main(string[] args)
{
TcpClient client = new TcpClient();
client.Connect("127.0.0.1", 9000);
Foo fo = new Foo();
fo.number = 10;
fo.str = "str";
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
formatter.Serialize(stream, fo);
byte[] buffer = new byte[2048];
stream.Read(buffer, 0, buffer.Length);
client.GetStream().Write(buffer, 0, buffer.Length);
}
}
How would I fix this?