通过网络流发送字节,值会发生变化

时间:2014-03-21 00:45:14

标签: c# java .net hex byte

模糊的标题,但我无法在标题中解释我的问题,因为我自己并不完全理解这个问题。

基本上,我在我的客户端通过网络流发送数据:

像这样:

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

因此idBytes在发送时包含{0,254,237,0}。但是当我收到服务器端时,它会更改为{0,253,253,0}。

这是我的服务器代码:

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

当我然后显示我收到的内容时:

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

我得到00-FD-FD-00

当它应该是00-FE-ED-00时,我一直在使用强制转换等等,但是当我将它们转换为一个字节时,中间字节被接收为65535然后是253。

任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:2)

StreamReader.Read读取具有该流的当前编码的字符(默认情况下为utf8),这不是必需的单字节,就像您的代码所假设的那样。

你应该:

  • 使用读取单个字节的方法,如Stream.ReadByte
  • 在写入流时使用StreamWriter(基本上读取和写入应该是彼此的镜像)