internal static void InitRead(WebConnection cnc) { StartRead(cnc) .ContinueWith(t => { if (t.IsFaulted) cnc.HandleError(WebExceptionStatus.UnknownError, t.Exception, "InitRead"); if (ReadState.Aborted == cnc.Data.ReadState) cnc.HandleError(WebExceptionStatus.ConnectFailure, null, "InitRead"); }); }
internal static async Task StartRead(WebConnection cnc) { try { await ReadDoneAsync(cnc); } catch (Exception e) { cnc.HandleError(WebExceptionStatus.ReceiveFailure, e, "StartRead"); } }
static async Task ReadDoneAsync(WebConnection cnc) { var nread = 0; var data = cnc.Data; var ns = cnc._nstream; if (ns == null) { cnc.Close(true); return; } var pos = -1; nread += cnc._position; if (data.ReadState == ReadState.None) { Exception exc = null; try { var result = await GetResponseAsync(cnc._nstream, data, cnc._sPoint).ConfigureAwait(false); } catch (Exception e) { exc = e; } if (exc != null) { cnc.HandleError(WebExceptionStatus.ServerProtocolViolation, exc, "ReadDone4"); return; } } if (data.ReadState == ReadState.Aborted) { cnc.HandleError(WebExceptionStatus.RequestCanceled, null, "ReadDone"); return; } if (data.ReadState != ReadState.Content) { var est = nread * 2; var max = (est < cnc._buffer.Length) ? cnc._buffer.Length : est; var newBuffer = new byte[max]; Buffer.BlockCopy(cnc._buffer, 0, newBuffer, 0, nread); cnc._buffer = newBuffer; cnc._position = nread; data.ReadState = ReadState.None; InitRead(cnc); return; } cnc._position = 0; var stream = new WebConnectionStream(cnc, data); var expectContent = ExpectContent(data.StatusCode, data.Request.Method); string tencoding = null; if (expectContent) tencoding = data.Headers["Transfer-Encoding"]; cnc._chunkedRead = (tencoding != null && tencoding.IndexOf("chunked", StringComparison.OrdinalIgnoreCase) != -1); if (!cnc._chunkedRead) { stream.ReadBuffer = cnc._buffer; stream.ReadBufferOffset = 0; stream.ReadBufferSize = nread; try { await stream.CheckResponseInBufferAsync().ConfigureAwait(false); } catch (Exception e) { cnc.HandleError(WebExceptionStatus.ReceiveFailure, e, "ReadDone7"); } } else if (cnc._chunkStream == null) { try { cnc._chunkStream = new ChunkStream(cnc._buffer, 0, nread, data.Headers); } catch (Exception e) { cnc.HandleError(WebExceptionStatus.ServerProtocolViolation, e, "ReadDone5"); return; } } else { cnc._chunkStream.ResetBuffer(); try { cnc._chunkStream.Write(cnc._buffer, 0, nread); } catch (Exception e) { cnc.HandleError(WebExceptionStatus.ServerProtocolViolation, e, "ReadDone6"); return; } } data.Stream = stream; if (!expectContent) stream.ForceCompletion(); await data.Request.SetResponseDataAsync(data).ConfigureAwait(false); }