September 9, 2004

Code Dipshit

I feel like such a major dipshit right now.

I'm working on an image broadcasting program right now. A client app connects via TCP to a server. The server then starts broadcasting back a frame type (full frame, diff frame, etc.) (Int32), the size of the frame (Int32), and then the data. The client only reads as much data as I tell it I'm going to send. (I'm securing it next...first step: get it working.)

Anyway, I create the image in a MemoryStream, and then ship it over the wire.

So, I had the following code (w is a BinaryWriter, ms is the MemoryStream):
w.Write(ms.Length)

w.Write(ms.ToArray)
Any guess as to what was happening? I was getting the wonderfully vague "Invalid parameter used" System.ArgumentException thrown in my face on the client side.

I couldn't understand it. So, I put in debug code to save the image as it was sent, and to save the data as it was received.

Both files were the same size, but the one on the client had four null bytes at the beginning, and four bytes of actual data stripped from the end.

It turns out that the MemoryStream.Length property is a Long (Int64), so the BinaryWriter.Write(Long) overload was taking over instead of BinaryWriter.Write(Integer). I replaced ms.Length with CInt(ms.Length), and all was well again.

Oh, well. It took me two hours to find the bug, but at least it's fixed.

No comments: