在c#客户端/服务器程序中,从服务器发送的数据在客户端接收时会发生更改

在c#客户端/服务器程序中,从服务器发送的数据在客户端接收时会发生更改,c#,network-programming,C#,Network Programming,服务器端代码: byte[] size = new byte[4]; size = BitConverter.GetBytes(fileData.Length); stream.Write(size, 0, 4); byte[] size = new byte[4]; ReadWholeArray(s, size); int fileSize = BitConverter.ToInt32(size, 0); 客户端代码: byte[] size = new byte[4]; size = B

服务器端代码:

byte[] size = new byte[4];
size = BitConverter.GetBytes(fileData.Length);
stream.Write(size, 0, 4);
byte[] size = new byte[4];
ReadWholeArray(s, size);
int fileSize = BitConverter.ToInt32(size, 0);
客户端代码:

byte[] size = new byte[4];
size = BitConverter.GetBytes(fileData.Length);
stream.Write(size, 0, 4);
byte[] size = new byte[4];
ReadWholeArray(s, size);
int fileSize = BitConverter.ToInt32(size, 0);
ReadWholeArray
方法的定义:

public static void ReadWholeArray(Stream stream, byte[] data)
{
    int offset = 0;
    int remaining = data.Length;
    while (remaining > 0)
    {
        int read = stream.Read(data, offset, remaining);
        if (read <= 0)
            throw new EndOfStreamException
                (String.Format("End of stream reached with {0} bytes left to read", remaining));
        remaining -= read;
        offset += read;
    }
}
公共静态void ReadWholeArray(流,字节[]数据)
{
整数偏移=0;
剩余整数=数据长度;
而(剩余>0)
{
int read=stream.read(数据、偏移量、剩余量);

如果(读好的,简单的诊断开始:在两端记录字节数组的各个内容,这样您就可以看到那里发生了什么

通过这种方式,您可以查看是二进制数据在您的通信协议中被破坏,还是
位转换器
导致了您的问题。例如,您可以在一端有一个大端名
位转换器
,在另一端有一个小端名
位转换器
。这似乎不太可能,但可能-特别是如果您的服务器或客户端运行的是Mono而不是.NET本身

如果这确实是个问题,那么您可能希望使用my
EndianBitConverter
class from,它允许您指定endianness

如果问题出现在通信层,您很可能希望安装以查看网络级别上发生的情况。例如,您确定您已经读取了到目前为止应该读取的所有数据吗?(如果在此之前您只读取了15个字节,并且大小写在偏移量16处,那么显然您将首先获得“额外”字节。)

这很好用:

private void button2_Click(object sender, RoutedEventArgs e)
{
    MemoryStream ms = new MemoryStream();
    byte [] original = BitConverter.GetBytes((int)2224); // 176, 8, 0, 0
    ms.Write(original, 0, original.Length);
    ms.Seek(0, SeekOrigin.Begin);
    byte [] data = new byte[4];
    int count = ms.Read(data, 0, 4); // count is 4, data is 176, 8, 0, 0
    int fileSize = BitConverter.ToInt32(data, 0); // is 2224
    return;
}
您是否可以使用WireShark或其他工具拦截字节?您使用的是哪种连接?是否可以发送更多数据(即流开头的telnet控制字符)?您是否可以调试每一端并验证这些值,或者将字节数组内容写入日志文件?通过调用此命令:“byte[]size=new byte[4];”是浪费,因为BitConverter.GetBytes()返回一个新数组