Search code examples
c#network-programmingmemorystreamnetworkstreambinaryformatter

memorystream copyto network stream issues


I'm having a problem with this code here.

using (MemoryStream ms = new MemoryStream())
{
    BinaryFormatter bf = new BinaryFormatter();
    bf.Serialize(ms,SerializableClassOfDoom);
    ms.Position = 0;
    byte[] messsize = BitConverter.GetBytes(ms.Length);
    ms.Write(messsize, 0, messsize.Length);
    NetworkStream ns = Sock.GetStream();
    ms.CopyTo(ns);
    //ms.Close();
}

I can't figure out what's happening here, or why it's not working. It seems like eather it doesn't copy, or it closes the network stream, or something.

I'm sorry, I've tried debugging it, but if anyone can see any obvious problem here, I would appreciate it.

By the way, the class serializes fine, and the MemoryStream contains the data, but for some reason doing a ms.CopyTo(ns) just doesn't seem to work?

Essentially what I want to do is serialize the class to the network stream, with the size of the serialized data preceding it. If someone has a better way to do this let me know!


Solution

  • You are resetting the stream position at the wrong time.

    In your case, you write the 'length' to the beginning of the stream.

    The following should work:

    using (MemoryStream ms = new MemoryStream())
    {
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(ms,SerializableClassOfDoom);
        byte[] messsize = BitConverter.GetBytes(ms.Length);
        ms.Write(messsize, 0, messsize.Length);
        ms.Position = 0;
        NetworkStream ns = Sock.GetStream();
        ms.CopyTo(ns);
    }
    

    Update:

    For writing 'length' to the start, use a temporary stream/byte[].

    Example:

    using (MemoryStream ms = new MemoryStream())
    {
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(ms,SerializableClassOfDoom);
        byte[] data = ms.ToArray();
        byte[] messsize = BitConverter.GetBytes(ms.Length);
        ms.Position = 0;
        ms.Write(messsize, 0, messsize.Length);
        ms.Write(data, 0, data.Length);
        ms.Position = 0; // again!
        NetworkStream ns = Sock.GetStream();
        ms.CopyTo(ns);
    }
    

    Update 2:

    More efficient way.

    using (MemoryStream ms = new MemoryStream())
    {
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(ms,SerializableClassOfDoom);
        byte[] messsize = BitConverter.GetBytes(ms.Length);
        NetworkStream ns = Sock.GetStream();
        ns.Write(messsize, 0, messsize.Length);
        ms.Position = 0; // not sure if needed, doc for CopyTo unclear
        ms.CopyTo(ns); 
    }