using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using YuncangTrace.LocalService.Services.Hik;
namespace YuncangTrace.LocalService.Services;
///
/// 本机 WebSocket 服务(只监听 127.0.0.1,默认端口 17301)
///
/// 给网页的实时预览 / 云台 / 拉通道用:以前走 HTTP(先 POST 建会话、再用 <img> 拉 MJPEG),
/// 跨域/代理/多标签场景下都要多一次请求,而且浏览器对 MJPEG 的复用不总是如意;WS 下一条连接可以:
/// - hello:拿服务名/版本/登录状态;
/// - get_channels:用 8000 私有协议登录 NVR 取通道;
/// - start_preview:建预览会话,之后服务端持续推**二进制 JPEG 帧**;
/// - stop_preview:停掉某一路上行,释放设备码流;
/// - open_window / close_window:在本机软件里开/关**满帧率原生窗口**(PlayM4 直接渲染)。
///
/// 帧格式(服务端 → 客户端,Binary):
/// [1 字节 sid 长度][sid ASCII][JPEG 原始字节]
/// 一条连接可同时推多路(多磁贴预览),按 sid 区分。
///
/// 文本消息统一 { id, action, ... },回复 { id, ok, data | message }。
///
/// ⚠️ 页面从 https 打开时,浏览器可能把 ws://127.0.0.1 当混合内容拦掉(目前没有 HTTP 预览兼底,
/// 遇到这种情况界面会提示无法连接):调用方应先把站点上到 https,或浏览器站点设置里放行本机回环地址。
///
public sealed class LocalWsServer : IDisposable
{
/// 监听端口(可用 YUNCANG_LOCAL_WS_PORT 临时覆盖)
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;
}
private readonly HttpListener _listener = new();
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)
{
_hik = hik;
_preview = preview;
_native = native;
}
/// 日志回调(服务线程 → UI 线程的桥)
public event Action? Log;
/// 当前是否已登录(hello 里返回)
public Func? IsLoggedInProvider { get; set; }
/// 当前登录用户显示名(hello 里返回)
public Func? UserNameProvider { get; set; }
public string Url => $"ws://127.0.0.1:{Port}/";
public bool IsRunning => _listener.IsListening;
/// 启动监听;端口被占/没权限会抛 (调用方只记日志,HTTP 仍可用)
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();
_cts = new CancellationTokenSource();
_loop = Task.Run(() => AcceptLoopAsync(_cts.Token));
Log?.Invoke($"WS 服务已启动:{Url}");
}
public void Stop()
{
if (!IsRunning) return;
try { _cts?.Cancel(); } catch { /* 忽略 */ }
try { _listener.Stop(); } catch { /* 忽略 */ }
try { _listener.Close(); } catch { /* 忽略 */ }
_cts?.Dispose();
_cts = null;
_loop = null;
Log?.Invoke("WS 服务已停止");
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
Stop();
_listener.Close();
}
// ==================== 接受连接 ====================
private async Task AcceptLoopAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested && _listener.IsListening)
{
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);
return;
}
WebSocket socket;
try
{
var wsContext = await context.AcceptWebSocketAsync(null).ConfigureAwait(false);
socket = wsContext.WebSocket;
}
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})");
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] 网页已断开");
}
}
private static async Task WriteProbeAsync(HttpListenerContext context)
{
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);
}
catch
{
// 探活失败不影响主流程
}
finally
{
try { context.Response.Close(); } 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(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);
}
}
}
/// 需要“不堵后面的消息”的 action
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 Jobs { get; } = new(StringComparer.OrdinalIgnoreCase);
/// 云台命令串行化(保证「开始转 → 停止」不会反序,否则摄像机会一直转)
public SemaphoreSlim DeviceLock { get; } = new(1, 1);
/// 本连接打开的原生预览窗口(页面断开时一并关闭)
public ConcurrentDictionary Windows { get; } = new(StringComparer.OrdinalIgnoreCase);
public async Task ReplyAsync(string? id, bool ok, object? data, CancellationToken ct, string? message = null)
{
var payload = new Dictionary
{
["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(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
{
if (Socket.State == WebSocketState.Open)
{
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; }
}
}