【问题标题】:Sending Bytes over networkstream, values changing通过网络流发送字节,值改变
【发布时间】:2014-04-28 04:35:23
【问题描述】:

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

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

像这样:

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。

任何帮助将不胜感激。

【问题讨论】:

    标签: c# java .net hex byte


    【解决方案1】:

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

    您应该:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-17
      • 2011-09-05
      • 1970-01-01
      • 1970-01-01
      • 2010-12-06
      • 2011-04-05
      相关资源
      最近更新 更多