本机 HTTP/WS 改用自建 TcpListener,不再依赖 HTTP.sys
现场机器上 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>
This commit is contained in:
parent
950b16a0dd
commit
8c83275719
@ -2,7 +2,7 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using YuncangTrace.LocalService.Services;
|
||||
@ -534,12 +534,12 @@ public partial class App : Application
|
||||
{
|
||||
_server.Start();
|
||||
}
|
||||
catch (HttpListenerException ex)
|
||||
catch (SocketException ex)
|
||||
{
|
||||
var hint = ex.ErrorCode switch
|
||||
var hint = ex.SocketErrorCode switch
|
||||
{
|
||||
5 => "没有绑定端口的权限。用管理员执行一次:netsh http add urlacl url=http://localhost:17300/ user=%USERNAME%",
|
||||
32 => "端口 17300 已被占用(可能还有一个本程序实例在跑)。",
|
||||
SocketError.AddressAlreadyInUse => $"端口 {LocalHttpServer.Port} 已被占用(可能还有一个本程序实例在跑)。",
|
||||
SocketError.AccessDenied => $"没有绑定端口 {LocalHttpServer.Port} 的权限(可能被安全软件拦截)。",
|
||||
_ => $"启动本机服务失败:{ex.Message}",
|
||||
};
|
||||
AppLog.Write(hint);
|
||||
@ -551,7 +551,7 @@ public partial class App : Application
|
||||
MessageBox.Show(ex.Message, "本机服务启动失败", MessageBoxButton.OK, MessageBoxImage.Warning);
|
||||
}
|
||||
|
||||
// WS 出问题不弹窗:网页会自动退回 HTTP 预览
|
||||
// WS 出问题不弹窗(HTTP 侧已经弹过/记过日志了),预览与云台会不可用,只记日志
|
||||
if (_wsServer is not null)
|
||||
{
|
||||
try
|
||||
@ -561,7 +561,7 @@ public partial class App : Application
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write($"[ws] 启动失败(网页将退回 HTTP 预览):{ex.Message}");
|
||||
AppLog.Write($"[ws] 启动失败(网页预览/云台不可用):{ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -23,7 +23,8 @@ desktop/
|
||||
├── LoginWindow.xaml / .xaml.cs # 账号 / 密码 / 记住账号 / 自动恢复登录(不展示服务地址)
|
||||
├── MainWindow.xaml / .xaml.cs # 服务状态、测试查询、菜单、退出登录
|
||||
└── Services/
|
||||
├── LocalHttpServer.cs # HttpListener(17300):查询 / 唤起登录 / 下载录像
|
||||
├── LocalHttpServer.cs # 本机 HTTP(17300):查询 / 唤起登录 / 下载录像
|
||||
├── LoopbackHttpServer.cs # 回环 HTTP/1.1 服务端(TcpListener 自实现,不依赖 HTTP.sys)
|
||||
├── LocalWsServer.cs # WebSocket(17301):拉通道 / 预览推帧 / 云台 / 满帧率窗口
|
||||
├── OrderQueryService.cs # ★ 按运单号查数据(接真实数据源的地方)
|
||||
├── ApiClient.cs # 登录 / 校验令牌(用到的全部后端接口)
|
||||
@ -362,8 +363,12 @@ cd desktop\installer
|
||||
### HTTP 17300(前端 `/local` 页用的就是这两个)
|
||||
|
||||
服务固定监听 `http://localhost:17300`(端口写在前端页面与插件里)。
|
||||
代码里**同时注册了 `http://127.0.0.1:17300/`** 前缀 —— `HttpListener` 只接受「注册过的 host」,
|
||||
不注册的话用 127.0.0.1 访问会直接被回 400(前端改 `VITE_LOCAL_SERVICE` 时就会碰到)。
|
||||
`LoopbackHttpServer` 直接监听 **127.0.0.1 和 ::1**,所以 `localhost` / `127.0.0.1` 两种写法都能连
|
||||
(前端改 `VITE_LOCAL_SERVICE` 时不会碰到「回 400」)。请求的 `Host` 不是回环地址会被直接断开。
|
||||
|
||||
> ⚠️ **别改回 `HttpListener`**:它依赖 HTTP.sys。现场机器上 HTTP 服务被安全软件/系统优化禁用,
|
||||
> 或者卡在 STOP_PENDING 时,`HttpListener.Start()` 会抛 `句柄无效(6)`,HTTP 与 WS 会**同时**起不来
|
||||
> (2026-10-23 升级 1.0.113 后的现场故障就是它)。自建 TcpListener 不需要 HTTP.sys / urlacl / 管理员权限。
|
||||
|
||||
浏览器直接打开 <http://localhost:17300/> 会看到一个说明页(列了接口,方便排查)。
|
||||
|
||||
@ -592,8 +597,9 @@ reg query "HKCU\Software\Classes\yuncang\shell\open\command"
|
||||
|
||||
| 现象 | 处理 |
|
||||
| --- | --- |
|
||||
| 启动报「没有绑定端口的权限」/ `Access is denied (5)` | 管理员执行 `netsh http add urlacl url=http://localhost:17300/ user=%USERNAME%`,或改成以当前用户身份运行 |
|
||||
| 报端口被占用(错误 32) | 已经开了一个实例(单实例会把参数转过去);检查任务管理器里的残留进程 |
|
||||
| 启动报「句柄无效」/ `句柄无效 (6)` | 老版本用 `HttpListener`(HTTP.sys)才会这样:系统的 HTTP 服务被禁用或卡在 STOP_PENDING。本次修复起本机服务改成自建 TcpListener,不再依赖 HTTP.sys;老版本临时处理可 `net start http` 或重启电脑 |
|
||||
| 启动报「没有绑定端口的权限」/ `Access is denied (5)` | 端口被安全软件拦了;换端口(`YUNCANG_LOCAL_PORT`)或加白名单 |
|
||||
| 报端口被占用(`AddressAlreadyInUse`) | 已经开了一个实例(单实例会把参数转过去);检查任务管理器里的残留进程 |
|
||||
| 网页提示服务不可用,但软件在跑 | 先用浏览器直接打开 `http://localhost:17300/api/query/`(会回 400 但带登录状态):打不开→防火墙/端口;打得开→多半是 CORS 头没回。预览类问题则看 `ws://127.0.0.1:17301/` 能不能打开(直接浏览器访问应该返回一小段 JSON) |
|
||||
| 点网页「启动本机软件」没反应 | 协议没注册(界面看「启动协议」状态);或浏览器拦了自动跳转(必须用户点击) |
|
||||
| 唤起时弹「You must install .NET Desktop Runtime」 | 唤起的是 `bin\Debug` 这类 framework-dependent 的 exe(拿不到 `DOTNET_ROOT`)。用自包含发布产物,并让它启动一次以校正注册表 |
|
||||
|
||||
@ -1,9 +1,6 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace YuncangTrace.LocalService.Services;
|
||||
@ -23,9 +20,9 @@ namespace YuncangTrace.LocalService.Services;
|
||||
/// 带 `Access-Control-Request-Private-Network: true` 的预检,必须回
|
||||
/// `Access-Control-Allow-Private-Network: true`,否则预检失败。
|
||||
///
|
||||
/// 用 <see cref="HttpListener"/>(HTTP.sys):绑定 `http://localhost:端口/` 一般不需要管理员权限;
|
||||
/// 若报「拒绝访问(5)」,用管理员执行一次:
|
||||
/// <c>netsh http add urlacl url=http://localhost:17300/ user=%USERNAME%</c>
|
||||
/// 监听用 <see cref="LoopbackHttpServer"/>(自建 TcpListener,127.0.0.1 + ::1)。
|
||||
/// **不要改回 <see cref="HttpListener"/>**:它依赖 HTTP.sys,现场机器上 HTTP 服务被禁用/卡住时
|
||||
/// 会抛「句柄无效(6)」,本机服务直接起不来(2026-10-23 升级 1.0.113 后的现场故障)。
|
||||
/// </summary>
|
||||
public sealed class LocalHttpServer : IDisposable
|
||||
{
|
||||
@ -38,10 +35,8 @@ public sealed class LocalHttpServer : IDisposable
|
||||
return int.TryParse(raw, out var port) && port is > 0 and < 65536 ? port : 17300;
|
||||
}
|
||||
|
||||
private readonly HttpListener _listener = new();
|
||||
private readonly LoopbackHttpServer _listener;
|
||||
private readonly OrderQueryService _queryService;
|
||||
private CancellationTokenSource? _cts;
|
||||
private Task? _loop;
|
||||
|
||||
/// <summary>
|
||||
/// 「按运单下载录像」服务(网页查件页也会调)
|
||||
@ -68,6 +63,7 @@ public sealed class LocalHttpServer : IDisposable
|
||||
public LocalHttpServer(OrderQueryService queryService)
|
||||
{
|
||||
_queryService = queryService;
|
||||
_listener = new LoopbackHttpServer(Port, HandleAsync, message => Log?.Invoke(message));
|
||||
}
|
||||
|
||||
/// <summary>是否已登录(网页靠它判断要不要唤起登录)</summary>
|
||||
@ -76,23 +72,16 @@ public sealed class LocalHttpServer : IDisposable
|
||||
/// <summary>浏览器里可直接打开的地址</summary>
|
||||
public string BaseUrl => $"http://localhost:{Port}";
|
||||
|
||||
public bool IsRunning => _listener.IsListening;
|
||||
public bool IsRunning => _listener.IsRunning;
|
||||
|
||||
/// <summary>启动监听;失败抛 <see cref="HttpListenerException"/>(端口被占 / 没权限)</summary>
|
||||
/// <summary>启动监听;端口被占/被拦抛 <see cref="System.Net.Sockets.SocketException"/></summary>
|
||||
public void Start()
|
||||
{
|
||||
if (IsRunning) return;
|
||||
|
||||
_listener.Prefixes.Clear();
|
||||
// 两个都监听:前端页面默认用 localhost,但改 VITE_LOCAL_SERVICE 用 127.0.0.1 时也得能连
|
||||
// (HttpListener 只接受 "注册过的 host",否则直接 400)
|
||||
_listener.Prefixes.Add($"{BaseUrl}/");
|
||||
_listener.Prefixes.Add($"http://127.0.0.1:{Port}/");
|
||||
// 127.0.0.1 和 ::1 都监听:前端默认写 localhost,换 VITE_LOCAL_SERVICE 用 127.0.0.1 时也得能连
|
||||
_listener.Start();
|
||||
|
||||
_cts = new CancellationTokenSource();
|
||||
_loop = Task.Run(() => AcceptLoopAsync(_cts.Token));
|
||||
|
||||
Log?.Invoke($"服务已启动:{BaseUrl}");
|
||||
}
|
||||
|
||||
@ -102,9 +91,7 @@ public sealed class LocalHttpServer : IDisposable
|
||||
|
||||
try
|
||||
{
|
||||
_cts?.Cancel();
|
||||
_listener.Stop();
|
||||
_listener.Close();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@ -116,49 +103,26 @@ public sealed class LocalHttpServer : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
private async Task AcceptLoopAsync(CancellationToken token)
|
||||
private async Task HandleAsync(LocalHttpRequest request, LocalHttpResponse response)
|
||||
{
|
||||
while (!token.IsCancellationRequested && _listener.IsListening)
|
||||
{
|
||||
HttpListenerContext context;
|
||||
try
|
||||
{
|
||||
context = await _listener.GetContextAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// Stop()/Close() 会让 GetContextAsync 抛异常,属于正常退出路径
|
||||
break;
|
||||
}
|
||||
|
||||
_ = Task.Run(() => HandleAsync(context), CancellationToken.None);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleAsync(HttpListenerContext context)
|
||||
{
|
||||
var request = context.Request;
|
||||
var response = context.Response;
|
||||
|
||||
try
|
||||
{
|
||||
WriteCorsHeaders(request, response);
|
||||
|
||||
// 预检请求(含 PNA 预检)直接放行
|
||||
if (request.HttpMethod.Equals("OPTIONS", StringComparison.OrdinalIgnoreCase))
|
||||
if (request.Method.Equals("OPTIONS", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
response.StatusCode = 204;
|
||||
response.Close();
|
||||
await response.WriteBytesAsync(204, null, Array.Empty<byte>()).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var path = request.Url?.AbsolutePath ?? "/";
|
||||
Log?.Invoke($"{request.HttpMethod} {path} ← {request.RemoteEndPoint?.Address}");
|
||||
var path = request.Path;
|
||||
Log?.Invoke($"{request.Method} {path} ← {request.RemoteAddress}");
|
||||
|
||||
// 网页请求唤起登录(POST,避免被浏览器的链接预取误触发)
|
||||
if (path.Equals("/api/activate-login", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (!request.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase))
|
||||
if (!request.Method.Equals("POST", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
await WriteJsonAsync(response, 405, new { ok = false, message = "请用 POST" }).ConfigureAwait(false);
|
||||
return;
|
||||
@ -186,7 +150,7 @@ public sealed class LocalHttpServer : IDisposable
|
||||
return;
|
||||
}
|
||||
|
||||
if (!request.HttpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase))
|
||||
if (!request.Method.Equals("GET", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
// 只剩 GET 接口了;旧的 POST /api/hik/* 会走到这里(预览/云台/拉通道已迁到 WS 17301)
|
||||
await WriteJsonAsync(response, 404, new
|
||||
@ -293,7 +257,11 @@ public sealed class LocalHttpServer : IDisposable
|
||||
Log?.Invoke($"处理请求出错:{ex.Message}");
|
||||
try
|
||||
{
|
||||
await WriteJsonAsync(response, 500, new { ok = false, message = "本机服务内部错误" }).ConfigureAwait(false);
|
||||
// 已经回过响应就不要再写一遍(会变成两个响应头拼在一条连接上)
|
||||
if (!response.Sent)
|
||||
{
|
||||
await WriteJsonAsync(response, 500, new { ok = false, message = "本机服务内部错误" }).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
@ -302,14 +270,7 @@ public sealed class LocalHttpServer : IDisposable
|
||||
}
|
||||
finally
|
||||
{
|
||||
try
|
||||
{
|
||||
response.Close();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 忽略
|
||||
}
|
||||
// 连接由 LoopbackHttpServer 在响应写完后关闭;这里不需要(也不应该)再 Close
|
||||
}
|
||||
}
|
||||
|
||||
@ -319,9 +280,9 @@ public sealed class LocalHttpServer : IDisposable
|
||||
/// 网页查件页(`/local?code=`)用:**任何装了本机软件的电脑**都能查件并下载录像,
|
||||
/// 存到**这台电脑自己设置的目录**(`~/packVideo/年/月/日/`),跟"是不是设备服务器"无关。
|
||||
/// </summary>
|
||||
private async Task HandlePlaybackDownloadAsync(HttpListenerRequest request, HttpListenerResponse response)
|
||||
private async Task HandlePlaybackDownloadAsync(LocalHttpRequest request, LocalHttpResponse response)
|
||||
{
|
||||
if (!request.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase))
|
||||
if (!request.Method.Equals("POST", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
await WriteJsonAsync(response, 405, new { ok = false, message = "请用 POST" }).ConfigureAwait(false);
|
||||
return;
|
||||
@ -354,8 +315,7 @@ public sealed class LocalHttpServer : IDisposable
|
||||
string code;
|
||||
try
|
||||
{
|
||||
using var reader = new StreamReader(request.InputStream, request.ContentEncoding ?? Encoding.UTF8);
|
||||
var body = await reader.ReadToEndAsync().ConfigureAwait(false);
|
||||
var body = Encoding.UTF8.GetString(request.Body);
|
||||
using var document = JsonDocument.Parse(string.IsNullOrWhiteSpace(body) ? "{}" : body);
|
||||
code = ReadJsonString(document.RootElement, "code") ?? string.Empty;
|
||||
}
|
||||
@ -418,10 +378,10 @@ public sealed class LocalHttpServer : IDisposable
|
||||
: null;
|
||||
|
||||
/// <summary>CORS + 私有网络访问(PNA)头</summary>
|
||||
private static void WriteCorsHeaders(HttpListenerRequest request, HttpListenerResponse response)
|
||||
private static void WriteCorsHeaders(LocalHttpRequest request, LocalHttpResponse response)
|
||||
{
|
||||
// 回显 Origin(比写死 * 更稳:以后要带 cookie/凭据也能用)
|
||||
var origin = request.Headers["Origin"];
|
||||
var origin = request.Header("Origin");
|
||||
response.Headers["Access-Control-Allow-Origin"] = string.IsNullOrEmpty(origin) ? "*" : origin;
|
||||
response.Headers["Vary"] = "Origin";
|
||||
// 只剩 GET / POST;漏了 POST 会导致预检直接失败(现象:网页报 CORS、实际服务在跑)
|
||||
@ -430,40 +390,32 @@ public sealed class LocalHttpServer : IDisposable
|
||||
response.Headers["Access-Control-Max-Age"] = "600";
|
||||
|
||||
// 公网页面访问 localhost 时,Chrome 会带 Access-Control-Request-Private-Network: true
|
||||
if (string.Equals(request.Headers["Access-Control-Request-Private-Network"], "true", StringComparison.OrdinalIgnoreCase))
|
||||
if (string.Equals(request.Header("Access-Control-Request-Private-Network"), "true", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
response.Headers["Access-Control-Allow-Private-Network"] = "true";
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task WriteJsonAsync(HttpListenerResponse response, int statusCode, object? payload)
|
||||
private static async Task WriteJsonAsync(LocalHttpResponse response, int statusCode, object? payload)
|
||||
{
|
||||
var body = JsonUtil.ToJson(payload);
|
||||
await WriteTextAsync(response, statusCode, "application/json; charset=utf-8", body).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static async Task WriteHtmlAsync(HttpListenerResponse response, int statusCode, string html)
|
||||
private static async Task WriteHtmlAsync(LocalHttpResponse response, int statusCode, string html)
|
||||
{
|
||||
await WriteTextAsync(response, statusCode, "text/html; charset=utf-8", html).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static async Task WriteTextAsync(HttpListenerResponse response, int statusCode, string contentType, string body)
|
||||
private static async Task WriteTextAsync(LocalHttpResponse response, int statusCode, string contentType, string body)
|
||||
{
|
||||
var bytes = Encoding.UTF8.GetBytes(body);
|
||||
|
||||
response.StatusCode = statusCode;
|
||||
response.ContentType = contentType;
|
||||
response.ContentEncoding = Encoding.UTF8;
|
||||
response.Headers["Cache-Control"] = "no-store";
|
||||
response.ContentLength64 = bytes.Length;
|
||||
|
||||
await response.OutputStream.WriteAsync(bytes).ConfigureAwait(false);
|
||||
await response.WriteTextAsync(statusCode, contentType, body).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Stop();
|
||||
_cts?.Dispose();
|
||||
_listener.Close();
|
||||
_listener.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,8 +2,8 @@ using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.WebSockets;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
@ -43,12 +43,14 @@ public sealed class LocalWsServer : IDisposable
|
||||
return int.TryParse(raw, out var port) && port is > 0 and < 65536 ? port : 17301;
|
||||
}
|
||||
|
||||
private readonly HttpListener _listener = new();
|
||||
/// <summary>RFC 6455 规定的握手固定串</summary>
|
||||
private const string WebSocketGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
||||
|
||||
private readonly LoopbackHttpServer _listener;
|
||||
private readonly HikDeviceService _hik;
|
||||
private readonly HikPreviewService _preview;
|
||||
private readonly HikNativePreviewService? _native;
|
||||
private CancellationTokenSource? _cts;
|
||||
private Task? _loop;
|
||||
private bool _disposed;
|
||||
|
||||
public LocalWsServer(HikDeviceService hik, HikPreviewService preview, HikNativePreviewService? native = null)
|
||||
@ -56,6 +58,7 @@ public sealed class LocalWsServer : IDisposable
|
||||
_hik = hik;
|
||||
_preview = preview;
|
||||
_native = native;
|
||||
_listener = new LoopbackHttpServer(Port, HandleContextAsync, message => Log?.Invoke(message));
|
||||
}
|
||||
|
||||
/// <summary>日志回调(服务线程 → UI 线程的桥)</summary>
|
||||
@ -69,38 +72,41 @@ public sealed class LocalWsServer : IDisposable
|
||||
|
||||
public string Url => $"ws://127.0.0.1:{Port}/";
|
||||
|
||||
public bool IsRunning => _listener.IsListening;
|
||||
public bool IsRunning => _listener.IsRunning;
|
||||
|
||||
/// <summary>启动监听;端口被占/没权限会抛 <see cref="HttpListenerException"/>(调用方只记日志,HTTP 仍可用)</summary>
|
||||
/// <summary>启动监听;端口被占/被拦会抛 <see cref="System.Net.Sockets.SocketException"/>(调用方只记日志)</summary>
|
||||
public void Start()
|
||||
{
|
||||
if (IsRunning) return;
|
||||
|
||||
_listener.Prefixes.Clear();
|
||||
_listener.Prefixes.Add($"http://localhost:{Port}/");
|
||||
_listener.Prefixes.Add($"http://127.0.0.1:{Port}/");
|
||||
_listener.Start();
|
||||
|
||||
// 自建 TCP 监听(127.0.0.1 + ::1)后自己完成 WebSocket 握手:不依赖 HTTP.sys
|
||||
// 先建令牌再开监听:早到的连接也能拿到可取消的令牌
|
||||
_cts = new CancellationTokenSource();
|
||||
_loop = Task.Run(() => AcceptLoopAsync(_cts.Token));
|
||||
try
|
||||
{
|
||||
_listener.Start();
|
||||
}
|
||||
catch
|
||||
{
|
||||
_cts.Dispose();
|
||||
_cts = null;
|
||||
throw;
|
||||
}
|
||||
|
||||
Log?.Invoke($"WS 服务已启动:{Url}");
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
if (!IsRunning) return;
|
||||
var wasRunning = IsRunning;
|
||||
|
||||
try { _cts?.Cancel(); } catch { /* 忽略 */ }
|
||||
|
||||
try { _listener.Stop(); } catch { /* 忽略 */ }
|
||||
try { _listener.Close(); } catch { /* 忽略 */ }
|
||||
|
||||
_cts?.Dispose();
|
||||
_cts = null;
|
||||
_loop = null;
|
||||
|
||||
Log?.Invoke("WS 服务已停止");
|
||||
if (wasRunning) Log?.Invoke("WS 服务已停止");
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
@ -108,53 +114,34 @@ public sealed class LocalWsServer : IDisposable
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
Stop();
|
||||
_listener.Close();
|
||||
_listener.Dispose();
|
||||
}
|
||||
|
||||
// ==================== 接受连接 ====================
|
||||
|
||||
private async Task AcceptLoopAsync(CancellationToken ct)
|
||||
private async Task HandleContextAsync(LocalHttpRequest request, LocalHttpResponse response)
|
||||
{
|
||||
while (!ct.IsCancellationRequested && _listener.IsListening)
|
||||
// 非 WS 请求:给网页/排障一个轻量探活(浏览器直接打开 ws://127.0.0.1:17301/ 就看这个)
|
||||
if (!request.IsWebSocketRequest)
|
||||
{
|
||||
HttpListenerContext context;
|
||||
try
|
||||
{
|
||||
context = await _listener.GetContextAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
break; // 监听被 Stop/Close
|
||||
}
|
||||
|
||||
_ = Task.Run(() => HandleContextAsync(context, ct), CancellationToken.None);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleContextAsync(HttpListenerContext context, CancellationToken ct)
|
||||
{
|
||||
// 非 WS 请求:给网页/排障一个轻量探活
|
||||
if (!context.Request.IsWebSocketRequest)
|
||||
{
|
||||
await WriteProbeAsync(context).ConfigureAwait(false);
|
||||
await WriteProbeAsync(response).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var ct = _cts?.Token ?? CancellationToken.None;
|
||||
WebSocket socket;
|
||||
try
|
||||
{
|
||||
var wsContext = await context.AcceptWebSocketAsync(null).ConfigureAwait(false);
|
||||
socket = wsContext.WebSocket;
|
||||
socket = await AcceptWebSocketAsync(request, response).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log?.Invoke($"[ws] 建立连接失败:{ex.Message}");
|
||||
try { context.Response.StatusCode = 400; context.Response.Close(); } catch { /* 忽略 */ }
|
||||
return;
|
||||
}
|
||||
|
||||
var conn = new Connection(socket);
|
||||
Log?.Invoke($"[ws] 网页已连接({context.Request.RemoteEndPoint})");
|
||||
Log?.Invoke($"[ws] 网页已连接({request.RemoteAddress})");
|
||||
|
||||
try
|
||||
{
|
||||
@ -181,25 +168,53 @@ public sealed class LocalWsServer : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task WriteProbeAsync(HttpListenerContext context)
|
||||
/// <summary>
|
||||
/// 在裸 TCP 连接上完成 WebSocket 握手,再交给 <see cref="WebSocket.CreateFromStream"/>
|
||||
///
|
||||
/// (HttpListener 会替我们做这一步,但它依赖 HTTP.sys;现在自己算 Sec-WebSocket-Accept)
|
||||
/// </summary>
|
||||
private static async Task<WebSocket> AcceptWebSocketAsync(LocalHttpRequest request, LocalHttpResponse response)
|
||||
{
|
||||
var key = request.Header("Sec-WebSocket-Key");
|
||||
if (string.IsNullOrWhiteSpace(key))
|
||||
{
|
||||
await response.WriteTextAsync(400, "text/plain; charset=utf-8", "缺少 Sec-WebSocket-Key").ConfigureAwait(false);
|
||||
throw new InvalidOperationException("缺少 Sec-WebSocket-Key");
|
||||
}
|
||||
|
||||
var accept = Convert.ToBase64String(SHA1.HashData(Encoding.ASCII.GetBytes(key.Trim() + WebSocketGuid)));
|
||||
|
||||
var handshake =
|
||||
"HTTP/1.1 101 Switching Protocols\r\n" +
|
||||
"Upgrade: websocket\r\n" +
|
||||
"Connection: Upgrade\r\n" +
|
||||
$"Sec-WebSocket-Accept: {accept}\r\n" +
|
||||
"\r\n";
|
||||
|
||||
await response.WriteRawAsync(Encoding.ASCII.GetBytes(handshake)).ConfigureAwait(false);
|
||||
|
||||
// 握手写完,这条连接的读写都归 WebSocket:HTTP 层别再兜底写响应
|
||||
response.Detach();
|
||||
|
||||
return WebSocket.CreateFromStream(response.Stream, new WebSocketCreationOptions
|
||||
{
|
||||
IsServer = true,
|
||||
KeepAliveInterval = TimeSpan.FromSeconds(30),
|
||||
});
|
||||
}
|
||||
|
||||
private static async Task WriteProbeAsync(LocalHttpResponse response)
|
||||
{
|
||||
try
|
||||
{
|
||||
var body = Encoding.UTF8.GetBytes("{\"ok\":true,\"ws\":true,\"name\":\"YuncangTrace\"}");
|
||||
context.Response.StatusCode = 200;
|
||||
context.Response.ContentType = "application/json; charset=utf-8";
|
||||
context.Response.Headers["Access-Control-Allow-Origin"] = "*";
|
||||
context.Response.ContentLength64 = body.Length;
|
||||
await context.Response.OutputStream.WriteAsync(body, 0, body.Length).ConfigureAwait(false);
|
||||
response.Headers["Access-Control-Allow-Origin"] = "*";
|
||||
await response.WriteTextAsync(200, "application/json; charset=utf-8",
|
||||
"{\"ok\":true,\"ws\":true,\"name\":\"YuncangTrace\"}").ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 探活失败不影响主流程
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { context.Response.Close(); } catch { /* 忽略 */ }
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 消息循环 ====================
|
||||
@ -599,7 +614,9 @@ public sealed class LocalWsServer : IDisposable
|
||||
|
||||
try
|
||||
{
|
||||
if (Socket.State == WebSocketState.Open)
|
||||
// CloseReceived 也要回一帧 Close:只 Dispose 的话浏览器会报
|
||||
// 「The remote party closed the WebSocket connection without completing the close handshake」
|
||||
if (Socket.State is WebSocketState.Open or WebSocketState.CloseReceived)
|
||||
{
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(2));
|
||||
await Socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "bye", timeout.Token)
|
||||
|
||||
593
desktop/Services/LoopbackHttpServer.cs
Normal file
593
desktop/Services/LoopbackHttpServer.cs
Normal file
@ -0,0 +1,593 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user