Domanda

Vague title, but I couldn't really explain my problem in the title, as I don't fully understand the problem myself.

Basically, I'm sending data over a network stream like so in my client:

Like so:

int id = 0x00FEED00;

byte[] idBytes = BitConvertor.GetBytes(id);

if (BitConverter.IsLittleEndian == true)
{
    Array.Reverse(bytes, 0, bytes.Length);
}

//the TcpClient and Network stream (GetStream) is initialised in my constructor
str.Write(idBytes, 0, idBytes.Length);
str.Flush();
stream.Close();

So the idBytes contains {0, 254, 237, 0} when sent. However on the the server side when I recieve it, it changes to {0, 253, 253, 0}.

This is my server code:

NetworkStream stream = client.GetStream();
StreamReader sr= new StreamReader(stream);
StreamWriter sw= new StreamWriter(stream);

List<byte> msg = new List<byte>();

 int numBytes= 0;
 while (reader.Peek() > -1)
 {
     try
     {
          int curr = sr.Read();
          msg.Add((byte)currByte);
          NumBytes++;
          Console.WriteLine((byte)curr);
      }
      catch
      {
          Console.WriteLine("Error");
      }

when I then display the contents of what I recieved like so:

string rec= BitConverter.ToString(msg.ToArray());

I get 00-FD-FD-00

when it should be 00-FE-ED-00, I've been medling hours with the casts and such, but the the middle bytes are received as 65535 and then 253 when I cast them to a byte.

Any help would be GREATLY appreciated.

È stato utile?

Soluzione

StreamReader.Read reads a character with current encoding for that stream (utf8 by default), which is not necessary single byte like your code assumes.

You should either:

  • use method that reads single byte like Stream.ReadByte
  • use StreamWriter when writing to the stream (basically read and write should be mirrors of each other)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top