Writing a 2-byte integer to a stream?

David Brown picture David Brown · Aug 26, 2009 · Viewed 7.2k times · Source

I'm trying to interact with an application over the network which uses a simple protocol. I have to send a header that looks like this:

2 bytes = Data Length (including Request Type)
1 byte = Request Type

I'm taking both parameters as integers:

private static void WriteHeader(Stream buf, int length, int requestType) {
    buf.Write(BitConverter.GetBytes(length), 0, 2);
    buf.WriteByte((byte)requestType);
}

I'm calling it like this:

byte[] outBuf = new byte[256];
using (MemoryStream outStream = new MemoryStream(outBuf)) {
    // Socket connection stuff here
    WriteHeader(outStream, 1, 110);
    sock.Send(outBuf);
    // Receive stuff here, never returns
}

I don't get any kind of exception when calling this method or sending outBuf over a socket, but the network application never responds. I can query it with other programs, though, so I'm fairly certain that it's because my header isn't being written correctly.

Am I doing something wrong when writing the values?

EDIT: Added MemoryStream code

Answer

Nader Shirazie picture Nader Shirazie · Aug 26, 2009

What type of stream is it? If its buffering your input, the data may never actually be sent across the wire.

Edit:

BitConverter.GetBytes(1) gives you [1, 0, 0, 0], from which you are passing [1,0]. Maybe its an endian-ness issue. Try sending [0,1] as your header.