http://www.developer.com/net/net/article.php/3331571/C-TIP-Converting-amp-Sending-Sockets-Data-with-a-Leading-Length-Value.htm
Most articles that illustrate how to send data via sockets tend to focus on sending and receiving simple textual data. While this is certainly useful, one very common practical need is to prefix a length value to the data being sent. However, when you start sending and receiving numeric data via sockets, you have to be aware of conversion issues in terms of what type of machine is on the other end of the connection. Specifically, you need to know how to convert numeric data from the local machine's format (host order) to the industry standard format for sending sockets data (network order). Basically, there are two main helper classes/methods that you'll need to know about when sending data over sockets. The first is the IPAddress.HostToNetworkOrder method. This method takes a value and converts it from the host (local machine's) format to network order (big-endian). Note that I didn't say that it converts little-endian to big-endian because there are times when the host order will be big-endian. It's always a good idea to convert to network order even if both machines use big-endian format because, as with today's abilities to move code from one platform to another, you never know when someone might want to run your code on a different platform than the one you originally designed it for. The second method is the Encoding class, which can be used to convert a String object into a byte array—as required by the Socket.Send method. Below I present to you a simple SendRequest method that takes a socket object and a string value to be sent and then prefixes the numeric value of the string's length to the data before sending it. The function performs the following steps:
C# TIP: Converting & Sending Sockets Data with a Leading Length Value
March 26, 2004
Note: If the terms host order, network order, little-endian, or big-endian are new to you or you'd like a refresher on these terms, please refer to my article entitled "Sockets Byte-Ordering Primer."
void SendRequest(Socket socket, string request)
{
// get string length
int reqLen = request.Length;
// convert string length value to network order
int reqLenH2N = IPAddress.HostToNetworkOrder(reqLen);
// get string length value into a byte array -- for use with
// Socket.Send
byte[] reqLenArray = BitConverter.GetBytes(reqLenH2N);
// send the length value
socket.Send(reqLenArray, 4, System.Net.Sockets.SocketFlags.None);
// copy string to a byte array
byte[] dataArray = Encoding.ASCII.GetBytes(request);
// send the string array
socket.Send(dataArray, reqLen,
System.Net.Sockets.SocketFlags.None);
}