现场机器上 HTTP 服务被安全软件/系统优化禁用或卡在 STOP_PENDING 时, HttpListener.Start() 抛「句柄无效(6)」,HTTP 17300 与 WS 17301 会同时起不来 (2026-10-23 升级 1.0.113 后的现场故障)。 - 新增 LoopbackHttpServer:TcpListener 直接监听 127.0.0.1 + ::1,自己解析 HTTP/1.1 请求, Host 不是回环地址的直接断开;不需要 urlacl / 管理员权限 - LocalHttpServer 改用它,请求处理不再直接摸 HttpListener 类型 - LocalWsServer 在同一层自己完成 WebSocket 握手(Sec-WebSocket-Accept), 再交给 WebSocket.CreateFromStream;关闭时 CloseReceived 也回一帧 Close, 避免浏览器报「未完成关闭握手」 - 启动失败的提示改成按 SocketError 判断(端口占用 / 无权限) - 已回过响应后不再兜底写 500(否则一条连接上会出现两个响应头) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
594 lines
20 KiB
C#
594 lines
20 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using System.IO;
|
||
using System.Net;
|
||
using System.Net.Sockets;
|
||
using System.Text;
|
||
using System.Threading;
|
||
using System.Threading.Tasks;
|
||
|
||
namespace YuncangTrace.LocalService.Services;
|
||
|
||
/// <summary>
|
||
/// 回环地址上的极简 HTTP/1.1 服务端(TcpListener + 手写报文解析)。
|
||
///
|
||
/// 为什么不用 <see cref="HttpListener"/>:它跑在 HTTP.sys 上。现场机器上 HTTP 服务被安全软件/系统优化
|
||
/// 禁用,或者卡在 STOP_PENDING(服务停不下来、也起不来)时,<c>HttpListener.Start()</c> 会抛
|
||
/// <c>HttpListenerException(6)「句柄无效」</c> —— 本机 HTTP 与 WebSocket 会**同时**起不来
|
||
/// (2026-10-23 现场升级到 1.0.113 后就是这个现象)。
|
||
///
|
||
/// 自己开 TCP 监听只依赖回环端口:不需要 HTTP.sys、不需要 urlacl、不需要管理员权限,
|
||
/// 端口被别的进程占了也只是普通的 <see cref="SocketException"/>。
|
||
///
|
||
/// 只监听 127.0.0.1 和 ::1(浏览器把 localhost 解析成哪个都能连上),一个请求一条连接,
|
||
/// 响应后由服务端关闭(<c>Connection: close</c>)—— 本机接口都是低频调用,够用且实现简单。
|
||
/// </summary>
|
||
internal sealed class LoopbackHttpServer : IDisposable
|
||
{
|
||
/// <summary>请求头上限(含请求行;正常请求远小于它)</summary>
|
||
private const int MaxHeaderBytes = 32 * 1024;
|
||
|
||
/// <summary>请求体上限(本机接口只有小 JSON)</summary>
|
||
private const int MaxBodyBytes = 4 * 1024 * 1024;
|
||
|
||
/// <summary>等请求头的超时:浏览器会预先建立连接(preconnect)却不发请求,不能一直占着</summary>
|
||
private static readonly TimeSpan RequestTimeout = TimeSpan.FromSeconds(30);
|
||
|
||
private readonly int _port;
|
||
private readonly Func<LocalHttpRequest, LocalHttpResponse, Task> _handler;
|
||
private readonly Action<string>? _log;
|
||
private readonly List<TcpListener> _listeners = new();
|
||
private CancellationTokenSource? _cts;
|
||
private Task? _acceptLoop;
|
||
private bool _disposed;
|
||
|
||
public LoopbackHttpServer(int port, Func<LocalHttpRequest, LocalHttpResponse, Task> handler, Action<string>? log = null)
|
||
{
|
||
_port = port;
|
||
_handler = handler;
|
||
_log = log;
|
||
}
|
||
|
||
public bool IsRunning { get; private set; }
|
||
|
||
/// <summary>启动监听;端口被占/被安全软件拦会抛 <see cref="SocketException"/>(调用方自己决定弹不弹窗)</summary>
|
||
public void Start()
|
||
{
|
||
if (IsRunning) return;
|
||
|
||
var started = new List<TcpListener>();
|
||
try
|
||
{
|
||
// IPv4 回环是主路径(前端写死 127.0.0.1);IPv6 回环让 localhost 解析到 ::1 的浏览器也能连
|
||
started.Add(Listen(IPAddress.Loopback));
|
||
try
|
||
{
|
||
started.Add(Listen(IPAddress.IPv6Loopback));
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_log?.Invoke($"[http] {_port} 端口的 IPv6 回环未监听(不影响 IPv4):{ex.Message}");
|
||
}
|
||
}
|
||
catch
|
||
{
|
||
foreach (var listener in started)
|
||
{
|
||
try { listener.Stop(); } catch { /* 忽略 */ }
|
||
}
|
||
throw;
|
||
}
|
||
|
||
_listeners.AddRange(started);
|
||
_cts = new CancellationTokenSource();
|
||
IsRunning = true;
|
||
|
||
// 传快照:Stop() 会清空 _listeners
|
||
var snapshot = _listeners.ToArray();
|
||
_acceptLoop = Task.Run(() => AcceptLoopAsync(snapshot, _cts.Token));
|
||
}
|
||
|
||
private TcpListener Listen(IPAddress address)
|
||
{
|
||
var listener = new TcpListener(address, _port);
|
||
listener.Start();
|
||
return listener;
|
||
}
|
||
|
||
public void Stop()
|
||
{
|
||
if (!IsRunning) return;
|
||
IsRunning = false;
|
||
|
||
try { _cts?.Cancel(); } catch { /* 忽略 */ }
|
||
|
||
foreach (var listener in _listeners)
|
||
{
|
||
try { listener.Stop(); } catch { /* 忽略 */ }
|
||
}
|
||
_listeners.Clear();
|
||
|
||
_cts?.Dispose();
|
||
_cts = null;
|
||
_acceptLoop = null;
|
||
}
|
||
|
||
public void Dispose()
|
||
{
|
||
if (_disposed) return;
|
||
_disposed = true;
|
||
Stop();
|
||
}
|
||
|
||
// ==================== 接受连接 ====================
|
||
|
||
private async Task AcceptLoopAsync(TcpListener[] listeners, CancellationToken ct)
|
||
{
|
||
var tasks = new List<Task>();
|
||
foreach (var listener in listeners)
|
||
{
|
||
tasks.Add(AcceptAsync(listener, ct));
|
||
}
|
||
|
||
try
|
||
{
|
||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||
}
|
||
catch
|
||
{
|
||
// Stop() 会让各监听退出,属于正常路径
|
||
}
|
||
}
|
||
|
||
private async Task AcceptAsync(TcpListener listener, CancellationToken ct)
|
||
{
|
||
while (!ct.IsCancellationRequested)
|
||
{
|
||
TcpClient client;
|
||
try
|
||
{
|
||
client = await listener.AcceptTcpClientAsync(ct).ConfigureAwait(false);
|
||
}
|
||
catch (OperationCanceledException)
|
||
{
|
||
break;
|
||
}
|
||
catch (ObjectDisposedException)
|
||
{
|
||
break;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
if (ct.IsCancellationRequested) break;
|
||
|
||
_log?.Invoke($"[http] 接受连接失败(继续监听):{ex.Message}");
|
||
try
|
||
{
|
||
await Task.Delay(50, ct).ConfigureAwait(false);
|
||
}
|
||
catch
|
||
{
|
||
break;
|
||
}
|
||
continue;
|
||
}
|
||
|
||
_ = Task.Run(() => HandleClientAsync(client, ct), CancellationToken.None);
|
||
}
|
||
}
|
||
|
||
private async Task HandleClientAsync(TcpClient client, CancellationToken ct)
|
||
{
|
||
using (client)
|
||
{
|
||
try
|
||
{
|
||
client.NoDelay = true;
|
||
using var stream = client.GetStream();
|
||
|
||
LocalHttpRequest? request;
|
||
using (var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct))
|
||
{
|
||
timeout.CancelAfter(RequestTimeout);
|
||
request = await LocalHttpRequest.ReadAsync(stream, timeout.Token).ConfigureAwait(false);
|
||
}
|
||
|
||
if (request is null) return; // 空连接 / 报文不合法:直接关掉
|
||
|
||
var response = new LocalHttpResponse(stream, request.Method);
|
||
await _handler(request, response).ConfigureAwait(false);
|
||
|
||
if (!response.Detached && !response.Sent)
|
||
{
|
||
await response.WriteTextAsync(500, "text/plain; charset=utf-8", "本机服务内部错误").ConfigureAwait(false);
|
||
}
|
||
}
|
||
catch (OperationCanceledException)
|
||
{
|
||
// 等请求头超时 / 服务停止
|
||
}
|
||
catch (IOException)
|
||
{
|
||
// 浏览器取消请求(页面刷新、关闭)——很常见,不记日志
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
if (!ct.IsCancellationRequested) _log?.Invoke($"[http] 处理连接出错:{ex.Message}");
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>解析完成的本机 HTTP 请求</summary>
|
||
internal sealed class LocalHttpRequest
|
||
{
|
||
/// <summary>请求头上限(含请求行)</summary>
|
||
private const int MaxHeaderBytes = 32 * 1024;
|
||
|
||
/// <summary>请求体上限</summary>
|
||
private const int MaxBodyBytes = 4 * 1024 * 1024;
|
||
|
||
private readonly Dictionary<string, string> _headers;
|
||
|
||
private LocalHttpRequest(string method, string target, string path, string query,
|
||
Dictionary<string, string> headers, byte[] body, string remoteAddress)
|
||
{
|
||
Method = method;
|
||
Target = target;
|
||
Path = path;
|
||
Query = query;
|
||
_headers = headers;
|
||
Body = body;
|
||
RemoteAddress = remoteAddress;
|
||
}
|
||
|
||
/// <summary>HTTP 方法(GET / POST / OPTIONS ...)</summary>
|
||
public string Method { get; }
|
||
|
||
/// <summary>原始请求目标(可能带查询串)</summary>
|
||
public string Target { get; }
|
||
|
||
/// <summary>URL 路径(不含查询串;保留 %XX 编码,和 HttpListener 的 AbsolutePath 一样由调用方决定要不要解码)</summary>
|
||
public string Path { get; }
|
||
|
||
/// <summary>查询串(不含 '?',没有就是空串)</summary>
|
||
public string Query { get; }
|
||
|
||
/// <summary>请求体(没有就是空数组)</summary>
|
||
public byte[] Body { get; }
|
||
|
||
/// <summary>对端地址(日志用)</summary>
|
||
public string RemoteAddress { get; }
|
||
|
||
public IReadOnlyDictionary<string, string> Headers => _headers;
|
||
|
||
public string? Header(string name) => _headers.TryGetValue(name, out var value) ? value : null;
|
||
|
||
/// <summary>是不是 WebSocket 升级请求</summary>
|
||
public bool IsWebSocketRequest
|
||
{
|
||
get
|
||
{
|
||
var connection = Header("Connection") ?? string.Empty;
|
||
return Method.Equals("GET", StringComparison.OrdinalIgnoreCase)
|
||
&& string.Equals(Header("Upgrade"), "websocket", StringComparison.OrdinalIgnoreCase)
|
||
&& connection.Contains("upgrade", StringComparison.OrdinalIgnoreCase);
|
||
}
|
||
}
|
||
|
||
/// <summary>读一条请求;空连接/报文不合法返回 null(调用方直接关连接)</summary>
|
||
public static async Task<LocalHttpRequest?> ReadAsync(Stream stream, CancellationToken ct)
|
||
{
|
||
var reader = new BufferedSocketReader(stream);
|
||
|
||
var requestLine = await reader.ReadLineAsync(MaxHeaderBytes, ct).ConfigureAwait(false);
|
||
if (string.IsNullOrEmpty(requestLine)) return null;
|
||
|
||
var parts = requestLine.Split(' ');
|
||
if (parts.Length < 3) return null;
|
||
|
||
var method = parts[0];
|
||
var target = parts[1];
|
||
|
||
var headers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||
var headerBytes = requestLine.Length;
|
||
|
||
while (true)
|
||
{
|
||
var line = await reader.ReadLineAsync(MaxHeaderBytes, ct).ConfigureAwait(false);
|
||
if (line is null) return null; // 连接半截断了
|
||
if (line.Length == 0) break; // 头部结束
|
||
|
||
headerBytes += line.Length;
|
||
if (headerBytes > MaxHeaderBytes) return null;
|
||
|
||
var colon = line.IndexOf(':');
|
||
if (colon <= 0) continue;
|
||
|
||
var name = line[..colon].Trim();
|
||
var value = line[(colon + 1)..].Trim();
|
||
if (name.Length == 0) continue;
|
||
|
||
// 重复头(如 Connection)合并,行为跟 HttpListener 一致
|
||
headers[name] = headers.TryGetValue(name, out var existing) ? existing + ", " + value : value;
|
||
}
|
||
|
||
// 只接受回环 Host(以前 HttpListener 只注册了 localhost/127.0.0.1,别的 Host 直接 400):
|
||
// 同时挡掉 DNS rebinding —— 恶意域名解析到 127.0.0.1 后带着自己的 Host 来打本机接口
|
||
if (headers.TryGetValue("Host", out var host) && host.Length > 0 && !IsLoopbackHost(host)) return null;
|
||
|
||
var queryIndex = target.IndexOf('?');
|
||
var path = queryIndex >= 0 ? target[..queryIndex] : target;
|
||
var query = queryIndex >= 0 ? target[(queryIndex + 1)..] : string.Empty;
|
||
|
||
// 绝对地址形式(代理/个别客户端会这么发)
|
||
if (Uri.TryCreate(target, UriKind.Absolute, out var absolute) && absolute.Scheme.StartsWith("http", StringComparison.OrdinalIgnoreCase))
|
||
{
|
||
path = absolute.AbsolutePath;
|
||
query = absolute.Query.TrimStart('?');
|
||
}
|
||
|
||
byte[] body = Array.Empty<byte>();
|
||
|
||
var chunked = headers.TryGetValue("Transfer-Encoding", out var transferEncoding)
|
||
&& transferEncoding.Contains("chunked", StringComparison.OrdinalIgnoreCase);
|
||
|
||
if (chunked)
|
||
{
|
||
var decoded = await ReadChunkedBodyAsync(reader, ct).ConfigureAwait(false);
|
||
if (decoded is null) return null;
|
||
body = decoded;
|
||
}
|
||
else if (headers.TryGetValue("Content-Length", out var contentLengthRaw)
|
||
&& long.TryParse(contentLengthRaw, out var contentLength))
|
||
{
|
||
if (contentLength < 0 || contentLength > MaxBodyBytes) return null;
|
||
|
||
if (contentLength > 0)
|
||
{
|
||
// 浏览器发大 body 前会等 100 Continue,不回它会一直卡着
|
||
if (headers.TryGetValue("Expect", out var expect)
|
||
&& expect.Contains("100-continue", StringComparison.OrdinalIgnoreCase))
|
||
{
|
||
var cont = Encoding.ASCII.GetBytes("HTTP/1.1 100 Continue\r\n\r\n");
|
||
await stream.WriteAsync(cont, ct).ConfigureAwait(false);
|
||
await stream.FlushAsync(ct).ConfigureAwait(false);
|
||
}
|
||
|
||
var read = await reader.ReadExactAsync((int)contentLength, ct).ConfigureAwait(false);
|
||
if (read is null) return null;
|
||
body = read;
|
||
}
|
||
}
|
||
|
||
var remote = (stream as NetworkStream)?.Socket.RemoteEndPoint?.ToString() ?? string.Empty;
|
||
return new LocalHttpRequest(method, target, path, query, headers, body, remote);
|
||
}
|
||
|
||
private static bool IsLoopbackHost(string host)
|
||
{
|
||
var value = host.Trim();
|
||
|
||
if (value.StartsWith('['))
|
||
{
|
||
var end = value.IndexOf(']');
|
||
if (end > 0) value = value[1..end];
|
||
}
|
||
else
|
||
{
|
||
// 去掉端口(IPv6 字面量有多个冒号,已在上面按方括号处理)
|
||
var colon = value.LastIndexOf(':');
|
||
if (colon > 0 && value.IndexOf(':') == colon) value = value[..colon];
|
||
}
|
||
|
||
return value.Equals("localhost", StringComparison.OrdinalIgnoreCase)
|
||
|| value == "127.0.0.1"
|
||
|| value == "::1";
|
||
}
|
||
|
||
private static async Task<byte[]?> ReadChunkedBodyAsync(BufferedSocketReader reader, CancellationToken ct)
|
||
{
|
||
using var body = new MemoryStream();
|
||
|
||
while (true)
|
||
{
|
||
var sizeLine = await reader.ReadLineAsync(1024, ct).ConfigureAwait(false);
|
||
if (sizeLine is null) return null;
|
||
|
||
var semicolon = sizeLine.IndexOf(';');
|
||
var hex = (semicolon >= 0 ? sizeLine[..semicolon] : sizeLine).Trim();
|
||
if (!int.TryParse(hex, System.Globalization.NumberStyles.HexNumber, null, out var size)) return null;
|
||
|
||
if (size == 0)
|
||
{
|
||
// 吃掉 trailer,直到空行
|
||
while (true)
|
||
{
|
||
var trailer = await reader.ReadLineAsync(MaxHeaderBytes, ct).ConfigureAwait(false);
|
||
if (trailer is null) return null;
|
||
if (trailer.Length == 0) break;
|
||
}
|
||
break;
|
||
}
|
||
|
||
if (body.Length + size > MaxBodyBytes) return null;
|
||
|
||
var data = await reader.ReadExactAsync(size, ct).ConfigureAwait(false);
|
||
if (data is null) return null;
|
||
body.Write(data, 0, data.Length);
|
||
|
||
var crlf = await reader.ReadLineAsync(8, ct).ConfigureAwait(false);
|
||
if (crlf is null) return null;
|
||
}
|
||
|
||
return body.ToArray();
|
||
}
|
||
}
|
||
|
||
/// <summary>本机 HTTP 响应(一个请求只发一次;发了之后由服务端关连接)</summary>
|
||
internal sealed class LocalHttpResponse
|
||
{
|
||
private static readonly Encoding Utf8 = new UTF8Encoding(false);
|
||
|
||
private readonly Stream _stream;
|
||
|
||
internal LocalHttpResponse(Stream stream, string requestMethod)
|
||
{
|
||
_stream = stream;
|
||
RequestMethod = requestMethod;
|
||
}
|
||
|
||
public string RequestMethod { get; }
|
||
|
||
/// <summary>响应头(必须在写出前设置)</summary>
|
||
public Dictionary<string, string> Headers { get; } = new(StringComparer.OrdinalIgnoreCase);
|
||
|
||
/// <summary>底层连接(WebSocket 握手后交给 <c>WebSocket.CreateFromStream</c>)</summary>
|
||
public Stream Stream => _stream;
|
||
|
||
/// <summary>是否已经写过响应</summary>
|
||
public bool Sent { get; private set; }
|
||
|
||
/// <summary>连接已被上层接管(WebSocket):HTTP 层不要再写兜底响应</summary>
|
||
public bool Detached { get; private set; }
|
||
|
||
private bool IsHead => RequestMethod.Equals("HEAD", StringComparison.OrdinalIgnoreCase);
|
||
|
||
public void Detach() => Detached = true;
|
||
|
||
public Task WriteTextAsync(int statusCode, string? contentType, string body)
|
||
=> WriteBytesAsync(statusCode, contentType, Utf8.GetBytes(body));
|
||
|
||
public async Task WriteBytesAsync(int statusCode, string? contentType, byte[] body)
|
||
{
|
||
var head = BuildHead(statusCode, contentType, body.Length);
|
||
await _stream.WriteAsync(head).ConfigureAwait(false);
|
||
if (!IsHead && body.Length > 0)
|
||
{
|
||
await _stream.WriteAsync(body).ConfigureAwait(false);
|
||
}
|
||
await _stream.FlushAsync().ConfigureAwait(false);
|
||
Sent = true;
|
||
}
|
||
|
||
/// <summary>原样写一段内容(WebSocket 101 握手用)</summary>
|
||
public async Task WriteRawAsync(byte[] bytes)
|
||
{
|
||
await _stream.WriteAsync(bytes).ConfigureAwait(false);
|
||
await _stream.FlushAsync().ConfigureAwait(false);
|
||
Sent = true;
|
||
}
|
||
|
||
private byte[] BuildHead(int statusCode, string? contentType, int contentLength)
|
||
{
|
||
var builder = new StringBuilder(256);
|
||
builder.Append("HTTP/1.1 ").Append(statusCode).Append(' ').Append(ReasonPhrase(statusCode)).Append("\r\n");
|
||
builder.Append("Date: ").Append(DateTime.UtcNow.ToString("R")).Append("\r\n");
|
||
|
||
// 204/304 按规范不能带实体
|
||
if (statusCode is not 204 and not 304)
|
||
{
|
||
builder.Append("Content-Length: ").Append(contentLength).Append("\r\n");
|
||
}
|
||
|
||
if (!string.IsNullOrEmpty(contentType))
|
||
{
|
||
builder.Append("Content-Type: ").Append(contentType).Append("\r\n");
|
||
}
|
||
|
||
builder.Append("Connection: close\r\n");
|
||
|
||
foreach (var header in Headers)
|
||
{
|
||
builder.Append(header.Key).Append(": ").Append(header.Value).Append("\r\n");
|
||
}
|
||
|
||
builder.Append("\r\n");
|
||
return Encoding.Latin1.GetBytes(builder.ToString());
|
||
}
|
||
|
||
private static string ReasonPhrase(int statusCode) => statusCode switch
|
||
{
|
||
200 => "OK",
|
||
204 => "No Content",
|
||
400 => "Bad Request",
|
||
401 => "Unauthorized",
|
||
404 => "Not Found",
|
||
405 => "Method Not Allowed",
|
||
413 => "Payload Too Large",
|
||
500 => "Internal Server Error",
|
||
503 => "Service Unavailable",
|
||
_ => "OK",
|
||
};
|
||
}
|
||
|
||
/// <summary>
|
||
/// 带缓冲的 socket 读取器:按行读头部、按长度读 body(不越过报文边界)
|
||
/// </summary>
|
||
internal sealed class BufferedSocketReader
|
||
{
|
||
private readonly Stream _stream;
|
||
private readonly byte[] _buffer = new byte[4096];
|
||
private int _start;
|
||
private int _end;
|
||
|
||
public BufferedSocketReader(Stream stream) => _stream = stream;
|
||
|
||
private async ValueTask<bool> FillAsync(CancellationToken ct)
|
||
{
|
||
if (_start < _end) return true;
|
||
|
||
_start = 0;
|
||
_end = await _stream.ReadAsync(_buffer.AsMemory(), ct).ConfigureAwait(false);
|
||
return _end > 0;
|
||
}
|
||
|
||
/// <summary>读一行(去掉 CRLF);连接断了返回 null</summary>
|
||
public async Task<string?> ReadLineAsync(int maxLength, CancellationToken ct)
|
||
{
|
||
var builder = new StringBuilder(64);
|
||
|
||
while (true)
|
||
{
|
||
if (!await FillAsync(ct).ConfigureAwait(false)) return null;
|
||
|
||
var current = _buffer[_start++];
|
||
if (current == (byte)'\n')
|
||
{
|
||
if (builder.Length > 0 && builder[^1] == '\r') builder.Length--;
|
||
return builder.ToString();
|
||
}
|
||
|
||
builder.Append((char)current);
|
||
if (builder.Length > maxLength) return null;
|
||
}
|
||
}
|
||
|
||
/// <summary>精确读 count 字节;连接提前断开返回 null</summary>
|
||
public async Task<byte[]?> ReadExactAsync(int count, CancellationToken ct)
|
||
{
|
||
if (count == 0) return Array.Empty<byte>();
|
||
|
||
var result = new byte[count];
|
||
var read = 0;
|
||
|
||
while (read < count)
|
||
{
|
||
if (_start < _end)
|
||
{
|
||
var take = Math.Min(_end - _start, count - read);
|
||
Buffer.BlockCopy(_buffer, _start, result, read, take);
|
||
_start += take;
|
||
read += take;
|
||
continue;
|
||
}
|
||
|
||
var n = await _stream.ReadAsync(result.AsMemory(read, count - read), ct).ConfigureAwait(false);
|
||
if (n == 0) return null;
|
||
read += n;
|
||
}
|
||
|
||
return result;
|
||
}
|
||
}
|