1

I got this error when I try to load something into the MemoryStream. I try to send a picture (in a byte stream) through the network over a server. But every time I try to send it, it says

The stream end was reached before the processing is completed.

The line with the error is marked in the code below

namespace Model_Library
{
    [Serializable]
    public class Package
    {
        public List<object> DATA;
        public int ID;
        public PackageType packetType;

        public Package(PackageType u_type, int u_ID)
        {
            DATA = new List<object>();
            this.ID = u_ID;
            this.packetType = u_type;
        }

        public Package(byte[] packetBytes)
        {
            using (MemoryStream ms = new MemoryStream(packetBytes))
            {
                BinaryFormatter bf = new BinaryFormatter();
                Package p = (Package)bf.Deserialize(ms); //Here is the error
                ID = p.ID;
                DATA = p.DATA;
                packetType = p.packetType;
            }
        }

        public byte[] toBytes()
        {
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            bf.Serialize(ms, this);
            byte[] bytes = ms.ToArray();
            ms.Close();
            return bytes;
        }
    }

    public enum PackageType
    {
        connect,  
        login,
        registration, 
        friends, 
        message,
        message_confirmation, 
        load_history, 
        search_friends,
        add_friend 
    }
}
Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
Tiremo
  • 11
  • 2
  • Try setting the stream position to the beginning of the stream – reggaeguitar Apr 13 '15 at 19:27
  • I tried already "ms.Position = 0;" but i got the same error – Tiremo Apr 13 '15 at 19:31
  • no errors running your code with a simple object? – Ewan Apr 13 '15 at 19:40
  • Exactly. I have no clue why I have this error only when I try to send a picture through the stream. – Tiremo Apr 13 '15 at 19:42
  • Maybe show your streaming / network send code... the error implies the bytes received is not the entire message, it finishes prematurely - is the length of the byte array presented to `.Deserialize` the same produced by `toBytes()`? – steve16351 Apr 13 '15 at 20:32
  • If it works for everything except when you're trying to send an image, then it's almost certain that the problem is with how you're converting your image to a `List`. It's highly unlikely that the error exists in the code you've shown. – Jim Mischel Apr 13 '15 at 21:02

1 Answers1

0

Make sure all of the data has been received over the network, you don't show it here, but are you using NetworkStream.DataAvailable then please read this answer as is goes into some of the details on how to manage reading data off the network -TcpClient.GetStream().DataAvailable returns false, but stream has more data

Community
  • 1
  • 1
wijobo
  • 1
  • 2