private static void OnDataRead(IAsyncResult ar) { MessageReadState state = (MessageReadState)ar.AsyncState; int n = state.Stream.EndRead(ar); state.DataLength += n; int index = state.DataLength; int length = state.Data.Length; if (index == length) { // We are done reading state.Finish(); } else if (n > 0) { // We still have body data to read state.Stream.BeginRead(state.Data, index, length - index, OnDataRead, state); } else { // The read is incomplete state.Finish(); } }
private static void OnHeaderRead(IAsyncResult ar) { MessageReadState state = (MessageReadState)ar.AsyncState; int n = state.Stream.EndRead(ar); state.HeaderLength += n; int index = state.HeaderLength; int length = state.Header.Length; if (index == length) { // Allocate the body. We are done reading the header byte[] data = new byte[state.GetDataLength()]; state.Data = data; state.Stream.BeginRead(data, 0, data.Length, OnDataRead, state); } else if (n > 0) { // Read the rest of the header state.Stream.BeginRead(state.Header, index, length - index, OnHeaderRead, state); } else { // The stream has ended, but we have not finished reading the header state.Finish(); } }