C# 通过网络流发送字节,值正在更改

C# 通过网络流发送字节,值正在更改,c#,java,.net,hex,byte,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 N

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

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

像这样:

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");
      }
我得到00-FD-FD-00

当它应该是00-FE-ED-00时,我已经花了好几个小时来处理强制转换之类的事情,但是中间的字节被接收为65535,然后当我将它们强制转换为一个字节时接收到253

任何帮助都将不胜感激。

读取该流当前编码的字符(默认为utf8),这不是代码假定的单字节所必需的

你应该:

  • 使用读取单字节的方法,如
  • 写入流时使用
    StreamWriter
    (基本上读写应该是彼此的镜像)
string rec= BitConverter.ToString(msg.ToArray());