Good morning folks!

In this post I want to talk about a bug I discovered in my TDP.BaseServices library, which I remember you can download here. This bug prevented from properly deserializing objects I sent through the NetworkStream object.

The problem was in the way I read data from a NetworkStream object.

If you browse the library in the class “SocketHelper” you will find the following method (at least in the previous version…):

 private static byte[] ReceiveVarData(Stream stream)
    int Recv;
    byte[] Datasize = new byte[4];
    Recv = stream.Read(Datasize, 0, Datasize.Length); 
    int Size = BitConverter.ToInt32(Datasize, 0);
    byte[] Data = new byte[Size];
    Recv = stream.Read(Data, 0, Size);
    return Data;

What’s wrong with it? The problem here is that the NetworkStream.Read method doesn’t guarantee that it will read the number of bytes you specify in the third parameter (the variable “Size” in the code above). So you always have to check the return value of the Read method, which returns the exact number of bytes read. If this number is less than the number you need to read, you have to call the Read method again to read the remaining part.

Since I had to make this fix, I took the opportunity to slightly modify the entire class, because I realized that the way I was sending and receiving the size of the message could suffer of the same problem.

If you download the new version of the library you should understand what I mean…

I apologize to the millions of developers who are using my library 🤣.