Search code examples
c#.netsocketsencodingmemorystream

After receiving string as memory stream and encoding, more chars are added


I built an app which receiving and sending data to server by the code below, and I noticed It's adding some chars to the string I send as MemoryStream when I'm getting the string back. Here's the code and the debugging information:

Client:

            while (true)
            {
                if (stream.DataAvailable)
                {
                    while ((i = stream.Read(ByteBuffer, 0, ByteBuffer.Length)) != 0)
                    {
                        ms.Write(ByteBuffer, 0, ByteBuffer.Length);
                        if (stream.DataAvailable)
                            continue;
                        else
                            break;
                    }
                    ToReturn = Encoding.ASCII.GetString(ms.ToArray());

                    return ToReturn;
                }
            }
        }

Server:

            MemoryStream response = new MemoryStream();
            response = Protocol.ProcessRequest(dataRecieved, ClientAddr);
            #endregion
            Console.WriteLine("Trying to send back response." + Encoding.ASCII.GetString(response.ToArray()));
            stream.Flush();
            response.WriteTo(stream);

I've checked with the debugger and what printed with the console: the sent information is just fine, for example: response.Id^Name^Type^SubType^Description^AddedBy^AddedDT^IsSpecial^Amount@1^VGA cable^cable^display^Very old and common display cable.^Aviv^14/01/2019 22:04:34^False^3345@2^HDMI cable^cable^display^newer and better display cable. can pass network, audio and info.^Aviv^14/01/2019 22:05:30^False^4793

but the info received on the other side of the socket (the client) was: Id^Name^Type^SubType^Description^AddedBy^AddedDT^IsSpecial^Amount@1^VGA cable^cable^display^Very old and common display cable.^Aviv^14/01/2019 22:04:34^False^3345@2^HDMI cable^cable^display^newer and better display cable. can pass network, audio and info.^Aviv^14/01/2019 22:05:30^False^4793alse^4

-with these (alse^4) few chars at the end. can anyone tell me what's the encoding problem? Thanks.

AGAIN: the output from the server is fine


Solution

  • //ms.Write(ByteBuffer, 0, ByteBuffer.Length);
      ms.Write(ByteBuffer, 0, i);