Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I've been having the same exception for the past three days now, and it's starting to drive me mad.

I am using TCP to send a serialized byte array over the Interwebz, and I then deserialize it. However, every second time deserializing the array it gives me an exception:

"Binary stream '0' does not contain a valid BinaryHeader. Possible causes are invalid stream or object version change between serialization and deserialization."

Both the project for the server, and the project for the client use the same referenced DLL(Project) as marked the solution for most of the cases that this exception occurs. I also have resetted the stream position which has also been marked as an answer. Besides that I even checked if the byte array changed over time and it has not.

Now before answering this please take note that this worked a few projects ago, and there is no difference to any of the methods I created, and also I even made a more complex class to serialize with a less chance of getting an error.

The object I'm attempting to serialize:
C#
[Serializable]
    public class PacketAudioUpdate : ISerializable
    {
        public string SoundBytes;

        public PacketAudioUpdate()
        {

        }

        protected PacketAudioUpdate(SerializationInfo info, StreamingContext context)
        {
            SoundBytes = info.GetString("soundbytes");
        }

        [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter =true)]
        public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("soundbytes", SoundBytes);
        }
    }



Serialization/Deserialization methods:
C#
public static byte[] ObjectToByteArray(Object obj)
{
    MemoryStream fs = new MemoryStream();
    BinaryFormatter formatter = new BinaryFormatter();
    formatter.Serialize(fs, obj);
    byte[] rval = fs.ToArray();
    fs.Close();
    return rval;
}
public static object ByteArrayToObject(Byte[] Buffer)
{
    BinaryFormatter formatter = new BinaryFormatter();
    MemoryStream stream = new MemoryStream(Buffer);
    stream.Position = 0;
    object rval = formatter.Deserialize(stream);
    stream.Close();
    return rval;
}


Exception log:
> Protocol.dll!Protocol.NetClient.HandleClient() Line 228 C#
>
C#
if (OnPacket != null)
    OnPacket(this, new OnPacketEvent(Packet, Client));


>
C#
void ChatClientClient_OnPacket(object sender, NetClient.OnPacketEvent e)
{
    object parObject = Conversion.ByteArrayToObject(e.Packet);

    if (OnPackageReceived != null)
        OnPackageReceived(this, new OnPackageReceivedEvent(parObject));
}


Edit:

This is how I send information:

C#
public void SendPacket(byte[] Packet)
{
    /* Writes the size of the packet, and afterwards the packet itself. */
    Client.GetStream().Write(BitConverter.GetBytes(Packet.Length), 0, BitConverter.GetBytes(Packet.Length).Length);
    Client.GetStream().Write(Packet, 0, Packet.Length);
}


This is how I receive information:
C#
public void HandleClient()
{
    /** Initialize variables. */
    int BytesRead = 0;
    int BufferSize = 0;
    Stream = Client.GetStream();
    datalength = new byte[4];

    while (true)
    {
        /* Read the lenght. */
        try
        {
            Stream.Read(datalength, 0, datalength.Length);
            BufferSize = BitConverter.ToInt32(datalength, 0);
        }
        catch { break; }

        if (BufferSize != 0)
        {
            /** Renew the variables. */
            BytesRead = 0;
            Packet = new byte[BufferSize];

            /** Read out the packet. */
            try
            {
                BytesRead = Stream.Read(Packet, 0, BufferSize);
            }
            catch { break; }

            /** Connection lost due to no packet. */
            if (BytesRead == 0)
            {
                break;
            }

            if (OnPacket != null)
                OnPacket(this, new OnPacketEvent(Packet, Client));
        }
        else
        {
            break;
        }
    }


    StopClient();
}
Posted
Updated 26-Oct-13 10:54am
v2
Comments
Sergey Alexandrovich Kryukov 26-Oct-13 20:32pm    
Why would you use a memory stream if you already have one as Client.GetStream?
Now, exception text suggests that you don't have a valid serialized data in stream. So, how do you know that the buffer in input contains the data you have serialized? Did you use the debugger?
—SA
Yvar Birx 26-Oct-13 20:37pm    
Yes, yes I have. Let me try your suggestion and use the clientstream. :)
Yvar Birx 26-Oct-13 20:48pm    
Cheers Sergey!

By using the Client stream instead of the new memory stream I am able to do this without errors. Once again, thank you for your help!

- Dimitri Nostalgia
thatraja 28-Oct-13 10:18am    
Use 'Reply' widget to reply him, only that'll notify him.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900