views:

42

answers:

2

Server side code:

byte[] size = new byte[4];
size = BitConverter.GetBytes(fileData.Length);
stream.Write(size, 0, 4);

Client side code:

byte[] size = new byte[4];
ReadWholeArray(s, size);
int fileSize = BitConverter.ToInt32(size, 0);

Definition of ReadWholeArray method:

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

The Program sends fileData.Length (the value for this instance is 2422) from server. On receiving this data at client side the value of received data is -772097985 Why the sent data is not received without alteration in value? What is the problem?

+2  A: 

Okay, simple diagnostics to start with: log the individual contents of the byte array at both ends, so you can see what's going on there.

That way you can see if it's the binary data which is getting corrupted in your communication protocol, or whether BitConverter is causing your problem. For example, you could have a big-endian BitConverter at one end, and a little-endian BitConverter at the other. That seems unlikely, but it's possible - particularly if one of your server or client is running Mono rather than .NET itself.

If that does turn out to be the problem, you might want to use my EndianBitConverter class from MiscUtil, which lets you specify the endianness.

If the problem is in the communications layer, you quite possibly want to install Wireshark to see what's happening at the network level. Are you sure you've read all the data you're meant to have read so far, for example? (If you've only read 15 bytes before this, and the size is written at offset 16, then obviously you'll get the "extra" byte first.)

Jon Skeet
A: 

This works fine:

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

Can you use WireShark or something to intercept the bytes? What kind of connection are you using? Could more data be being sent (i.e. telnet control characters at the start of the stream)? Can you debug each end and verify these values or write the byte array contents to a log file? By the way calling this: "byte[] size = new byte[4];" is wasteful because BitConverter.GetBytes() returns a new array.

Jason Goemaat