简体   繁体   中英

Receiving garbled data when reading a NetworkStream in C#

I'm trying to receive data using a TcpListener in C# . I have the listener working, but when I make a HTTP request to it using my web browser, I just get garbled data when converted to ASCII. It seems like its skipping bytes?

while (client.Connected)
{
    if (stream.ReadByte() != -1)
    {
        Console.WriteLine("Recieving data");
        byte[] buf = new byte[0];
        byte data;
        while (stream.ReadByte() != -1)
        {
            data = (byte) stream.ReadByte();
            Console.Write("{0} ", data.ToString("x"));
            buf.Append(data);
        }
        dataRecieved(buf);
    }
}

Output:

54 2f 48 54 2f 2e d 48 73 3a 6c 63 6c 6f 74 38 38 d 43 6e 65 74 6f 3a 6b 65 2d 6c 76 d 43 63 65 43 6e 72 6c 20 61 2d 67 3d d 55 67 61 65 49 73 63 72 2d 65 75 73 73 20 d 55 65 2d 67 6e 3a 4d 7a 6c 61 35 30 28 69 64 77 20 54 31 2e 3b 57 6e 34 20 36 29 41 70 65 65 4b 74 35 37 33 20 4b 54 4c 20 69 65 47 63 6f 20 68 6f 65 31 33 30 35 36 2e 33 20 61 61 69 35 37 33 d 41 63 70 2d 61 67 61 65 20 6e 55 d 41 63 70 3a 74 78 2f 74 6c 61 70 69 61 69 6e 78 74 6c 78 6c 61 70 69 61 69 6e 78 6c 71 30 39 69 61 65 61 69 2c 6d 67 2f 65 70 69 61 65 61 6e 2c 2f 3b 3d 2e 2c 70 6c 63 74 6f 2f 69 6e 64 65 63 61 67 3b 3d 33 71 30 39 a 65 2d 50 3a 31 a 65 2d 65 63 2d 69 65 20 6f 65 a 65 2d 65 63 2d 6f 65 20 61 69 61 65 a 65 2d 65 63 2d 73 72 20 31 a 65 2d 65 63 2d 65 74 20 6f 75 65 74 a 63 65 74 45 63 64 6e 3a 67 69 2c 64 66 61 65 20 72 a a

Any ideas on how to make this work?

It is likely that you are getting UTF8 Data from the stream. You will have to deal with the encoding

Try something like this.


private string ReadUTF8String(Stream stream)
{
    using var ms = new MemoryStream();
    var buffer = new byte[4096];
    int readCount;
    while ((readCount = stream.Read(buffer)) > 0)
    {
        ms.Write(buffer, 0, readCount);
    }

    return Encoding.UTF8.GetString(ms.ToArray());
}


while (client.Connected)
{
    if (stream.ReadByte() != -1)
    {
        Console.WriteLine("Recieving data");
        string result = ReadUTF8String(stream);
        Console.Write(result);
    }
}


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM