private async Task <HttpRequest> ReadRequsetLine() { using (var timeout = new CancellationTokenSource(3000)) { timeout.Token.Register(() => Ns.Close()); string requestLine = null; using (var sr = new StreamReader(Ns, Encoding.ASCII, false, 65535, true)) { requestLine = await sr.ReadLineAsync(); if (string.IsNullOrEmpty(requestLine)) { return(null); } // Discard all other headers while (true) { var dummy = await sr.ReadLineAsync(); if (string.IsNullOrEmpty(dummy)) { break; } } } if (requestLine != null) { var m = requestLineMatcher.Match(requestLine); if (m.Success) { var result = new HttpRequest { Method = m.Groups[1].Value, RawUri = m.Groups[2].Value }; try { result.DecodedUri = new Uri(new Uri("http://localhost/"), result.RawUri); } catch (FormatException) { // The Uri may be invalid } return(result); } } } return(null); }
protected async Task SendTextRensponse(string status, string mimeType, string content) { var contentBytes = Encoding.UTF8.GetBytes(content); var header = "HTTP/1.1 " + status + "\r\n" + "Cache-Control: no-cache\r\n" + "Content-Length: " + contentBytes.Length.ToString(CultureInfo.InvariantCulture) + "\r\n" + "Content-Type: " + mimeType + "\r\n\r\n"; var headerBytes = Encoding.ASCII.GetBytes(header); using (var timeout = new CancellationTokenSource(3000)) { timeout.Token.Register(() => Ns.Close()); await Ns.WriteAsync(headerBytes, 0, headerBytes.Length); await Ns.WriteAsync(contentBytes, 0, contentBytes.Length); await Ns.FlushAsync(); } }