I\'ve been looking everywhere for examples on how to deal with TCP message framing. I see many examples where NetworkStreams are passed into a StreamReader or StreamWriter o
Prefixing the chunks with a length is better than using a separator character. You don't have to deal with any sort of escaping in order to send data with a newline that way.
This answer might not be relevant to you now, because it uses features from the AsyncCTP, which will only be in the next version of .net. However, it does make things much more concise. Essentially you write exactly the code you'd do for the synchronous case, but insert 'await' statements where there are asynchronous calls.
public static async Task ReadChunkAsync(this Stream me) {
var size = BitConverter.ToUInt32(await me.ReadExactAsync(4), 0);
checked {
return await me.ReadExactAsync((int)size);
}
}
public static async Task ReadExactAsync(this Stream me, int count) {
var buf = new byte[count];
var t = 0;
while (t < count) {
var n = await me.ReadAsync(buf, t, count - t);
if (n <= 0) {
if (t > 0) throw new IOException("End of stream (fragmented)");
throw new IOException("End of stream");
}
t += n;
}
return buf;
}
public static void WriteChunk(this Stream me, byte[] buffer, int offset, int count) {
me.Write(BitConverter.GetBytes(count), 0, 4);
me.Write(buffer, offset, count);
}