现场机器上 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>
647 lines
25 KiB
C#
647 lines
25 KiB
C#
using System;
|
||
using System.Collections.Concurrent;
|
||
using System.Collections.Generic;
|
||
using System.IO;
|
||
using System.Net.WebSockets;
|
||
using System.Security.Cryptography;
|
||
using System.Text;
|
||
using System.Text.Json;
|
||
using System.Threading;
|
||
using System.Threading.Tasks;
|
||
using YuncangTrace.LocalService.Services.Hik;
|
||
|
||
namespace YuncangTrace.LocalService.Services;
|
||
|
||
/// <summary>
|
||
/// 本机 WebSocket 服务(只监听 127.0.0.1,默认端口 <b>17301</b>)
|
||
///
|
||
/// 给网页的实时预览 / 云台 / 拉通道用:以前走 HTTP(先 POST 建会话、再用 <img> 拉 MJPEG),
|
||
/// 跨域/代理/多标签场景下都要多一次请求,而且浏览器对 MJPEG 的复用不总是如意;WS 下一条连接可以:
|
||
/// - <c>hello</c>:拿服务名/版本/登录状态;
|
||
/// - <c>get_channels</c>:用 8000 私有协议登录 NVR 取通道;
|
||
/// - <c>start_preview</c>:建预览会话,之后服务端持续推**二进制 JPEG 帧**;
|
||
/// - <c>stop_preview</c>:停掉某一路上行,释放设备码流;
|
||
/// - <c>open_window</c> / <c>close_window</c>:在本机软件里开/关**满帧率原生窗口**(PlayM4 直接渲染)。
|
||
///
|
||
/// 帧格式(服务端 → 客户端,Binary):
|
||
/// <code>[1 字节 sid 长度][sid ASCII][JPEG 原始字节]</code>
|
||
/// 一条连接可同时推多路(多磁贴预览),按 sid 区分。
|
||
///
|
||
/// 文本消息统一 <c>{ id, action, ... }</c>,回复 <c>{ id, ok, data | message }</c>。
|
||
///
|
||
/// ⚠️ 页面从 https 打开时,浏览器可能把 <c>ws://127.0.0.1</c> 当混合内容拦掉(目前没有 HTTP 预览兼底,
|
||
/// 遇到这种情况界面会提示无法连接):调用方应先把站点上到 https,或浏览器站点设置里放行本机回环地址。
|
||
/// </summary>
|
||
public sealed class LocalWsServer : IDisposable
|
||
{
|
||
/// <summary>监听端口(可用 <c>YUNCANG_LOCAL_WS_PORT</c> 临时覆盖)</summary>
|
||
public static int Port { get; } = ResolvePort();
|
||
|
||
private static int ResolvePort()
|
||
{
|
||
var raw = Environment.GetEnvironmentVariable("YUNCANG_LOCAL_WS_PORT");
|
||
return int.TryParse(raw, out var port) && port is > 0 and < 65536 ? port : 17301;
|
||
}
|
||
|
||
/// <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 bool _disposed;
|
||
|
||
public LocalWsServer(HikDeviceService hik, HikPreviewService preview, HikNativePreviewService? native = null)
|
||
{
|
||
_hik = hik;
|
||
_preview = preview;
|
||
_native = native;
|
||
_listener = new LoopbackHttpServer(Port, HandleContextAsync, message => Log?.Invoke(message));
|
||
}
|
||
|
||
/// <summary>日志回调(服务线程 → UI 线程的桥)</summary>
|
||
public event Action<string>? Log;
|
||
|
||
/// <summary>当前是否已登录(hello 里返回)</summary>
|
||
public Func<bool>? IsLoggedInProvider { get; set; }
|
||
|
||
/// <summary>当前登录用户显示名(hello 里返回)</summary>
|
||
public Func<string?>? UserNameProvider { get; set; }
|
||
|
||
public string Url => $"ws://127.0.0.1:{Port}/";
|
||
|
||
public bool IsRunning => _listener.IsRunning;
|
||
|
||
/// <summary>启动监听;端口被占/被拦会抛 <see cref="System.Net.Sockets.SocketException"/>(调用方只记日志)</summary>
|
||
public void Start()
|
||
{
|
||
if (IsRunning) return;
|
||
|
||
// 自建 TCP 监听(127.0.0.1 + ::1)后自己完成 WebSocket 握手:不依赖 HTTP.sys
|
||
// 先建令牌再开监听:早到的连接也能拿到可取消的令牌
|
||
_cts = new CancellationTokenSource();
|
||
try
|
||
{
|
||
_listener.Start();
|
||
}
|
||
catch
|
||
{
|
||
_cts.Dispose();
|
||
_cts = null;
|
||
throw;
|
||
}
|
||
|
||
Log?.Invoke($"WS 服务已启动:{Url}");
|
||
}
|
||
|
||
public void Stop()
|
||
{
|
||
var wasRunning = IsRunning;
|
||
|
||
try { _cts?.Cancel(); } catch { /* 忽略 */ }
|
||
try { _listener.Stop(); } catch { /* 忽略 */ }
|
||
|
||
_cts?.Dispose();
|
||
_cts = null;
|
||
|
||
if (wasRunning) Log?.Invoke("WS 服务已停止");
|
||
}
|
||
|
||
public void Dispose()
|
||
{
|
||
if (_disposed) return;
|
||
_disposed = true;
|
||
Stop();
|
||
_listener.Dispose();
|
||
}
|
||
|
||
// ==================== 接受连接 ====================
|
||
|
||
private async Task HandleContextAsync(LocalHttpRequest request, LocalHttpResponse response)
|
||
{
|
||
// 非 WS 请求:给网页/排障一个轻量探活(浏览器直接打开 ws://127.0.0.1:17301/ 就看这个)
|
||
if (!request.IsWebSocketRequest)
|
||
{
|
||
await WriteProbeAsync(response).ConfigureAwait(false);
|
||
return;
|
||
}
|
||
|
||
var ct = _cts?.Token ?? CancellationToken.None;
|
||
WebSocket socket;
|
||
try
|
||
{
|
||
socket = await AcceptWebSocketAsync(request, response).ConfigureAwait(false);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Log?.Invoke($"[ws] 建立连接失败:{ex.Message}");
|
||
return;
|
||
}
|
||
|
||
var conn = new Connection(socket);
|
||
Log?.Invoke($"[ws] 网页已连接({request.RemoteAddress})");
|
||
|
||
try
|
||
{
|
||
await ReceiveLoopAsync(conn, ct).ConfigureAwait(false);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Log?.Invoke($"[ws] 连接异常:{ex.Message}");
|
||
}
|
||
finally
|
||
{
|
||
// 页面关掉/刷新 → 它开的满帧率窗口一并关掉(否则码流会一直占着)
|
||
if (_native is not null && !conn.Windows.IsEmpty)
|
||
{
|
||
foreach (var wid in conn.Windows.Keys)
|
||
{
|
||
try { _native.Close(wid); } catch { /* 忽略 */ }
|
||
}
|
||
conn.Windows.Clear();
|
||
}
|
||
|
||
await conn.CloseAsync().ConfigureAwait(false);
|
||
Log?.Invoke("[ws] 网页已断开");
|
||
}
|
||
}
|
||
|
||
/// <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
|
||
{
|
||
response.Headers["Access-Control-Allow-Origin"] = "*";
|
||
await response.WriteTextAsync(200, "application/json; charset=utf-8",
|
||
"{\"ok\":true,\"ws\":true,\"name\":\"YuncangTrace\"}").ConfigureAwait(false);
|
||
}
|
||
catch
|
||
{
|
||
// 探活失败不影响主流程
|
||
}
|
||
}
|
||
|
||
// ==================== 消息循环 ====================
|
||
|
||
private async Task ReceiveLoopAsync(Connection conn, CancellationToken ct)
|
||
{
|
||
var buffer = new byte[16 * 1024];
|
||
using var message = new MemoryStream();
|
||
|
||
while (!ct.IsCancellationRequested && conn.Socket.State == WebSocketState.Open)
|
||
{
|
||
var result = await conn.Socket.ReceiveAsync(new ArraySegment<byte>(buffer), ct).ConfigureAwait(false);
|
||
|
||
if (result.MessageType == WebSocketMessageType.Close) break;
|
||
if (result.MessageType == WebSocketMessageType.Binary) continue; // 上行目前只收 JSON
|
||
|
||
message.Write(buffer, 0, result.Count);
|
||
if (message.Length > 256 * 1024)
|
||
{
|
||
// 异常大包直接丢掉,避免被刷内存
|
||
message.SetLength(0);
|
||
if (!result.EndOfMessage) continue;
|
||
}
|
||
|
||
if (!result.EndOfMessage) continue;
|
||
|
||
var text = Encoding.UTF8.GetString(message.ToArray());
|
||
message.SetLength(0);
|
||
|
||
// 慢命令(建会话/拉通道/开窗/云台)放后台并发执行,否则会把后面的
|
||
// 「停止预览 / 云台停转」堵在接收循环里(建会话要 1~2 秒,拖云台会明显卡)。
|
||
if (IsSlowAction(text))
|
||
{
|
||
_ = Task.Run(() => HandleTextAsync(conn, text, ct), CancellationToken.None);
|
||
}
|
||
else
|
||
{
|
||
await HandleTextAsync(conn, text, ct).ConfigureAwait(false);
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>需要“不堵后面的消息”的 action</summary>
|
||
private static bool IsSlowAction(string text)
|
||
{
|
||
try
|
||
{
|
||
using var doc = JsonDocument.Parse(text);
|
||
return GetString(doc.RootElement, "action") is "start_preview" or "get_channels" or "open_window" or "ptz" or "ptz_preset";
|
||
}
|
||
catch
|
||
{
|
||
return false;
|
||
}
|
||
}
|
||
|
||
private async Task HandleTextAsync(Connection conn, string text, CancellationToken ct)
|
||
{
|
||
string? id = null;
|
||
try
|
||
{
|
||
using var doc = JsonDocument.Parse(text);
|
||
var root = doc.RootElement;
|
||
|
||
if (root.TryGetProperty("id", out var idEl)) id = idEl.ToString();
|
||
var action = GetString(root, "action");
|
||
|
||
switch (action)
|
||
{
|
||
case "hello":
|
||
await conn.ReplyAsync(id, true, new
|
||
{
|
||
name = "YuncangTrace",
|
||
version = typeof(LocalWsServer).Assembly.GetName().Version?.ToString() ?? "0.0.0",
|
||
port = Port,
|
||
loggedIn = IsLoggedInProvider?.Invoke() ?? false,
|
||
user = UserNameProvider?.Invoke(),
|
||
}, ct).ConfigureAwait(false);
|
||
break;
|
||
|
||
case "ping":
|
||
await conn.ReplyAsync(id, true, new { pong = true }, ct).ConfigureAwait(false);
|
||
break;
|
||
|
||
case "get_channels":
|
||
{
|
||
var (host, port, user, password) = ReadDevice(root);
|
||
var data = await Task.Run(() => _hik.GetChannels(host, port, user, password), ct)
|
||
.ConfigureAwait(false);
|
||
await conn.ReplyAsync(id, true, data, ct).ConfigureAwait(false);
|
||
break;
|
||
}
|
||
|
||
case "start_preview":
|
||
{
|
||
var (host, port, user, password) = ReadDevice(root);
|
||
var channel = GetInt(root, "channel", 0);
|
||
if (channel <= 0) throw new ArgumentException("channel 必须是正整数");
|
||
|
||
var fps = GetInt(root, "fps", 25);
|
||
var streamType = GetInt(root, "streamType", 0);
|
||
var logical = GetInt(root, "logicalChannel", 0);
|
||
var mode = GetString(root, "mode") ?? "stream";
|
||
var name = GetString(root, "name");
|
||
|
||
var session = await Task.Run(() => _preview.Create(host, port, user, password, channel,
|
||
fps, logical > 0 ? logical : null, name, mode, streamType), ct).ConfigureAwait(false);
|
||
|
||
var job = new StreamJob(session);
|
||
if (!conn.Jobs.TryAdd(session.Id, job))
|
||
{
|
||
_preview.Remove(session.Id);
|
||
throw new InvalidOperationException("预览会话冲突,请重试");
|
||
}
|
||
|
||
job.Task = Task.Run(() => StreamLoopAsync(conn, job, job.Cts.Token), CancellationToken.None);
|
||
|
||
await conn.ReplyAsync(id, true, new
|
||
{
|
||
sid = session.Id,
|
||
channel = session.Channel,
|
||
logicalChannel = session.LogicalChannel,
|
||
streamId = session.StreamId,
|
||
mode = session.Mode,
|
||
fps = session.Fps,
|
||
streamType = session.StreamType,
|
||
warning = session.Warning,
|
||
}, ct).ConfigureAwait(false);
|
||
break;
|
||
}
|
||
|
||
case "stop_preview":
|
||
{
|
||
var sid = GetString(root, "sid");
|
||
if (!string.IsNullOrWhiteSpace(sid)) StopJob(conn, sid!);
|
||
await conn.ReplyAsync(id, true, new { sid }, ct).ConfigureAwait(false);
|
||
break;
|
||
}
|
||
|
||
case "open_window":
|
||
{
|
||
if (_native is null) throw new InvalidOperationException("本机软件未启用预览窗口");
|
||
|
||
var (host, port, user, password) = ReadDevice(root);
|
||
var channel = GetInt(root, "channel", 0);
|
||
if (channel <= 0) throw new ArgumentException("channel 必须是正整数");
|
||
|
||
var streamType = GetInt(root, "streamType", 0);
|
||
var name = GetString(root, "name");
|
||
|
||
var window = await Task.Run(
|
||
() => _native.Open(host, port, user, password, channel, streamType, name), ct).ConfigureAwait(false);
|
||
|
||
Log?.Invoke($"[ws] 满帧率窗口已打开:{host} 通道 {channel}(wid={window.Id})");
|
||
conn.Windows.TryAdd(window.Id, 0);
|
||
|
||
await conn.ReplyAsync(id, true, new
|
||
{
|
||
wid = window.Id,
|
||
host = window.Host,
|
||
channel = window.Channel,
|
||
streamType = window.StreamType,
|
||
mode = "window",
|
||
fps = 25,
|
||
message = "已在本机软件里打开满帧率预览窗口",
|
||
}, ct).ConfigureAwait(false);
|
||
break;
|
||
}
|
||
|
||
case "close_window":
|
||
{
|
||
var wid = GetString(root, "wid");
|
||
var closed = _native?.Close(wid) ?? false;
|
||
if (!string.IsNullOrWhiteSpace(wid)) conn.Windows.TryRemove(wid!, out _);
|
||
await conn.ReplyAsync(id, true, new { wid, closed }, ct).ConfigureAwait(false);
|
||
break;
|
||
}
|
||
|
||
case "ptz":
|
||
case "ptz_preset":
|
||
{
|
||
var (host, port, user, password) = ReadDevice(root);
|
||
var channel = GetInt(root, "channel", 0);
|
||
if (channel <= 0) throw new ArgumentException("channel 必须是正整数");
|
||
|
||
var speed = GetInt(root, "speed", 4);
|
||
|
||
// 云台命令串行化:保证「开始转 / 停转」的先后顺序(并发的 stop 可能先执行)
|
||
await conn.DeviceLock.WaitAsync(ct).ConfigureAwait(false);
|
||
try
|
||
{
|
||
if (action == "ptz_preset")
|
||
{
|
||
var presetAction = GetString(root, "presetAction") ?? "goto";
|
||
var preset = GetInt(root, "preset", 0);
|
||
|
||
await Task.Run(() => _hik.PtzPreset(host, port, user, password, channel, presetAction, preset), ct)
|
||
.ConfigureAwait(false);
|
||
|
||
await conn.ReplyAsync(id, true, new { channel, presetAction, preset }, ct).ConfigureAwait(false);
|
||
}
|
||
else
|
||
{
|
||
var command = GetString(root, "command");
|
||
if (string.IsNullOrWhiteSpace(command)) throw new ArgumentException("command 不能为空");
|
||
|
||
var stop = GetBool(root, "stop", false);
|
||
|
||
await Task.Run(() => _hik.PtzControl(host, port, user, password, channel, command!, stop, speed), ct)
|
||
.ConfigureAwait(false);
|
||
|
||
await conn.ReplyAsync(id, true, new { channel, command, stop, speed }, ct).ConfigureAwait(false);
|
||
}
|
||
}
|
||
finally
|
||
{
|
||
conn.DeviceLock.Release();
|
||
}
|
||
|
||
break;
|
||
}
|
||
|
||
default:
|
||
await conn.ReplyAsync(id, false, null, ct, "未知 action").ConfigureAwait(false);
|
||
break;
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
await conn.ReplyAsync(id, false, null, ct, ex.Message).ConfigureAwait(false);
|
||
}
|
||
}
|
||
|
||
private void StopJob(Connection conn, string sid)
|
||
{
|
||
if (!conn.Jobs.TryRemove(sid, out var job)) return;
|
||
|
||
try { job.Cts.Cancel(); } catch { /* 忽略 */ }
|
||
_preview.Remove(sid);
|
||
Log?.Invoke($"[ws] 预览已停止:{sid}");
|
||
}
|
||
|
||
// ==================== 推帧 ====================
|
||
|
||
private async Task StreamLoopAsync(Connection conn, StreamJob job, CancellationToken ct)
|
||
{
|
||
var session = job.Session;
|
||
var interval = TimeSpan.FromMilliseconds(1000.0 / Math.Max(1, session.Fps));
|
||
var next = DateTime.UtcNow;
|
||
|
||
try
|
||
{
|
||
while (!ct.IsCancellationRequested && conn.Socket.State == WebSocketState.Open)
|
||
{
|
||
byte[] frame;
|
||
try
|
||
{
|
||
frame = await Task.Run(() => _preview.CaptureFrame(session), ct).ConfigureAwait(false);
|
||
}
|
||
catch (OperationCanceledException)
|
||
{
|
||
break;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Log?.Invoke($"[ws] 取帧失败({session.Id}):{ex.Message}");
|
||
await Task.Delay(500, ct).ConfigureAwait(false);
|
||
continue;
|
||
}
|
||
|
||
if (frame.Length > 0)
|
||
{
|
||
session.Touch();
|
||
await conn.SendFrameAsync(session.Id, frame, ct).ConfigureAwait(false);
|
||
}
|
||
|
||
next = next.Add(interval);
|
||
var wait = next - DateTime.UtcNow;
|
||
if (wait < TimeSpan.Zero) wait = TimeSpan.Zero;
|
||
await Task.Delay(wait, ct).ConfigureAwait(false);
|
||
}
|
||
}
|
||
catch (OperationCanceledException)
|
||
{
|
||
// 正常停止
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Log?.Invoke($"[ws] 推流异常({session.Id}):{ex.Message}");
|
||
}
|
||
finally
|
||
{
|
||
conn.Jobs.TryRemove(session.Id, out _);
|
||
_preview.Remove(session.Id);
|
||
}
|
||
}
|
||
|
||
// ==================== 参数读取 ====================
|
||
|
||
private static (string Host, int Port, string User, string Password) ReadDevice(JsonElement root)
|
||
{
|
||
var host = GetString(root, "host") ?? GetString(root, "ip");
|
||
var user = GetString(root, "user") ?? GetString(root, "username") ?? GetString(root, "account");
|
||
var password = GetString(root, "password") ?? GetString(root, "pwd");
|
||
var port = GetInt(root, "port", 8000);
|
||
|
||
if (string.IsNullOrWhiteSpace(host)) throw new ArgumentException("host 不能为空");
|
||
if (string.IsNullOrWhiteSpace(user)) throw new ArgumentException("user 不能为空");
|
||
if (string.IsNullOrWhiteSpace(password)) throw new ArgumentException("password 不能为空");
|
||
|
||
return (host!, port, user!, password!);
|
||
}
|
||
|
||
private static string? GetString(JsonElement root, string name)
|
||
=> root.TryGetProperty(name, out var el) && el.ValueKind == JsonValueKind.String
|
||
? el.GetString()
|
||
: null;
|
||
|
||
private static int GetInt(JsonElement root, string name, int fallback)
|
||
{
|
||
if (!root.TryGetProperty(name, out var el)) return fallback;
|
||
if (el.ValueKind == JsonValueKind.Number && el.TryGetInt32(out var number)) return number;
|
||
return el.ValueKind == JsonValueKind.String && int.TryParse(el.GetString(), out var parsed) ? parsed : fallback;
|
||
}
|
||
|
||
private static bool GetBool(JsonElement root, string name, bool fallback)
|
||
{
|
||
if (!root.TryGetProperty(name, out var el)) return fallback;
|
||
if (el.ValueKind is JsonValueKind.True or JsonValueKind.False) return el.GetBoolean();
|
||
return el.ValueKind == JsonValueKind.String && bool.TryParse(el.GetString(), out var parsed) ? parsed : fallback;
|
||
}
|
||
|
||
// ==================== 连接 / 会话 ====================
|
||
|
||
private sealed class Connection
|
||
{
|
||
private readonly SemaphoreSlim _sendLock = new(1, 1);
|
||
|
||
public Connection(WebSocket socket) => Socket = socket;
|
||
|
||
public WebSocket Socket { get; }
|
||
|
||
public ConcurrentDictionary<string, StreamJob> Jobs { get; } = new(StringComparer.OrdinalIgnoreCase);
|
||
|
||
/// <summary>云台命令串行化(保证「开始转 → 停止」不会反序,否则摄像机会一直转)</summary>
|
||
public SemaphoreSlim DeviceLock { get; } = new(1, 1);
|
||
|
||
/// <summary>本连接打开的原生预览窗口(页面断开时一并关闭)</summary>
|
||
public ConcurrentDictionary<string, byte> Windows { get; } = new(StringComparer.OrdinalIgnoreCase);
|
||
|
||
public async Task ReplyAsync(string? id, bool ok, object? data, CancellationToken ct, string? message = null)
|
||
{
|
||
var payload = new Dictionary<string, object?>
|
||
{
|
||
["id"] = id,
|
||
["ok"] = ok,
|
||
["data"] = data,
|
||
["message"] = message,
|
||
};
|
||
|
||
var json = JsonSerializer.Serialize(payload);
|
||
var bytes = Encoding.UTF8.GetBytes(json);
|
||
await SendAsync(bytes, WebSocketMessageType.Text, ct).ConfigureAwait(false);
|
||
}
|
||
|
||
public Task SendFrameAsync(string sid, byte[] frame, CancellationToken ct)
|
||
{
|
||
var sidBytes = Encoding.ASCII.GetBytes(sid);
|
||
var buffer = new byte[1 + sidBytes.Length + frame.Length];
|
||
buffer[0] = (byte)sidBytes.Length;
|
||
Buffer.BlockCopy(sidBytes, 0, buffer, 1, sidBytes.Length);
|
||
Buffer.BlockCopy(frame, 0, buffer, 1 + sidBytes.Length, frame.Length);
|
||
return SendAsync(buffer, WebSocketMessageType.Binary, ct);
|
||
}
|
||
|
||
private async Task SendAsync(byte[] buffer, WebSocketMessageType type, CancellationToken ct)
|
||
{
|
||
await _sendLock.WaitAsync(ct).ConfigureAwait(false);
|
||
try
|
||
{
|
||
if (Socket.State != WebSocketState.Open) return;
|
||
await Socket.SendAsync(new ArraySegment<byte>(buffer), type, true, ct).ConfigureAwait(false);
|
||
}
|
||
finally
|
||
{
|
||
_sendLock.Release();
|
||
}
|
||
}
|
||
|
||
public async Task CloseAsync()
|
||
{
|
||
foreach (var job in Jobs.Values)
|
||
{
|
||
try { job.Cts.Cancel(); } catch { /* 忽略 */ }
|
||
}
|
||
Jobs.Clear();
|
||
|
||
try
|
||
{
|
||
// 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)
|
||
.ConfigureAwait(false);
|
||
}
|
||
}
|
||
catch
|
||
{
|
||
// 忽略
|
||
}
|
||
finally
|
||
{
|
||
Socket.Dispose();
|
||
// ⚠️ 不要 Dispose _sendLock:推流任务可能晚一步才退出,Dispose 会让它们抛 ObjectDisposedException
|
||
}
|
||
}
|
||
}
|
||
|
||
private sealed class StreamJob
|
||
{
|
||
public StreamJob(HikPreviewSession session) => Session = session;
|
||
|
||
public HikPreviewSession Session { get; }
|
||
public CancellationTokenSource Cts { get; } = new();
|
||
public Task? Task { get; set; }
|
||
}
|
||
}
|