接收字符串作为内存流并进行编码后,将添加更多字符

时间:2019-02-17 16:56:50

标签: c# .net sockets encoding memorystream

我构建了一个应用程序,该应用程序通过下面的代码接收和发送数据到服务器,我注意到,当我取回字符串时,它在以MemoryStream发送的字符串中添加了一些字符。这是代码和调试信息:

客户:

            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;
                }
            }
        }

服务器:

            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);

我已经检查了调试器以及控制台打印的内容: 发送的信息很好,例如: 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

,但是在套接字另一端(客户端)上收到的信息是: 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

-最后有几个(alse^4)个字符。谁能告诉我编码问题是什么?谢谢。

再次:服务器的输出很好

1 个答案:

答案 0 :(得分:2)

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