| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714 |
- using System;
- using System.Globalization;
- using System.IO;
- using System.Net;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using BeiJingComService.Core;
- using BeiJingComService.Infrastructure;
- namespace BeiJingComService.Protocols
- {
- /// <summary>
- /// HTTP 通道(本机 127.0.0.1)。
- /// 端点:
- /// POST /api/com/invoke 通用调用,body {"func":"...","args":["..."]}
- /// 返回 {"code","message","elapsedMs","output"}
- /// POST /api/com/open 便捷端点,等价于调用 COM 的 open
- /// POST /api/com/close 便捷端点,等价于调用 COM 的 close
- /// POST /api/card/read 读卡:服务端封装 open→GetPersonClass_Multimedia
- /// →GetPersonInfo(Nation)_Multimedia。
- /// body {"input":"<内层XML>"} 或 {"payload":"<完整XML>"}
- /// 可选 {"card_class":"1|2"}:调用方已知人员类别时传入,
- /// 传了则跳过 GetPersonClass_Multimedia,直接调参保信息
- /// 可选 {"session":"perRead|keepOpen"}:perRead(默认)用完即关;
- /// keepOpen 本次读卡序列不空闲关会话(只 Open 一次,测试用)。
- /// 该标志随本次请求走,不会残留影响其它入口。
- /// 返回体含 cardClass / funcName / cardNo / sessionMode
- /// (Round49 起不再有 cacheHit,服务端不设本地缓存)
- /// POST /api/scan/take 取走「扫码预捕获」缓冲里的码(Round54)。
- /// 消费式:取走即清空;超过 ScanCaptureTtlMs 视为过期未命中。
- /// 返回 {"code":0,"data":{"hit":bool,"value":"...","ageMs":n}}
- /// 码是医保支付凭证,服务端只回给调用方,不写日志不落盘
- /// GET /health 健康状态(真实网关状态,非硬编码)
- /// GET /debug HTML 调试页(托盘「HTML 调试」入口打开,与接口同源,
- /// 规避 file:// → 127.0.0.1 的 Private Network Access 拦截)
- /// POST /admin/reinitialize 重建网关(COM 实例、工作线程)
- /// GET /admin/config 当前配置(令牌不回显)
- /// 支持 CORS 与 OPTIONS 预检,便于浏览器/Cef/WebView2 前端直接调用。
- /// </summary>
- public class HttpProtocol : ITransportProtocol
- {
- /// <summary>内嵌调试页资源名:RootNamespace + 目录 + 文件名</summary>
- private const string DebugPageResource = "BeiJingComService.Html.com-debug.html";
- private readonly int _port;
- private HttpListener _listener;
- private CancellationTokenSource _cts;
- private Task _listenerTask;
- public string Name
- {
- get { return "Http"; }
- }
- public int Port
- {
- get { return _port; }
- }
- public bool IsListening
- {
- get { return _listener != null && _listener.IsListening; }
- }
- public HttpProtocol(int port)
- {
- _port = port;
- }
- public void Start()
- {
- _listener = new HttpListener();
- _listener.Prefixes.Add($"http://127.0.0.1:{_port}/");
- _listener.Start();
- _cts = new CancellationTokenSource();
- _listenerTask = Task.Run(() => ListenLoop(_cts.Token));
- Logger.Info($"HTTP 协议已启动: http://127.0.0.1:{_port}/");
- }
- public void Stop()
- {
- try { if (_cts != null) _cts.Cancel(); }
- catch { }
- try { if (_listener != null) _listener.Stop(); }
- catch (Exception ex) { Logger.Error("停止 HTTP 监听异常", ex); }
- try { if (_listenerTask != null) _listenerTask.Wait(TimeSpan.FromSeconds(2)); }
- catch { }
- Logger.Info("HTTP 协议已停止");
- }
- private async Task ListenLoop(CancellationToken token)
- {
- while (_listener != null && _listener.IsListening && !token.IsCancellationRequested)
- {
- try
- {
- HttpListenerContext context = await _listener.GetContextAsync();
- var ignored = Task.Run(() => HandleContextAsync(context));
- }
- catch (HttpListenerException) { break; }
- catch (OperationCanceledException) { break; }
- catch (ObjectDisposedException) { break; }
- catch (Exception ex) { Logger.Error("HTTP 监听异常", ex); }
- }
- }
- private async Task HandleContextAsync(HttpListenerContext context)
- {
- try
- {
- string path = context.Request.Url.AbsolutePath.ToLowerInvariant().TrimEnd('/');
- string method = context.Request.HttpMethod.ToUpperInvariant();
- if (method == "OPTIONS")
- {
- WriteJson(context, 204, "");
- return;
- }
- // 调试页放在令牌校验之前:它是静态 HTML,不含任何业务数据;
- // 若放在后面,一旦 AccessToken 非空,页面本身就打不开、也无法输入令牌自救。
- // 页面内发起的 /api/com/invoke 等接口调用,仍然走下面的 CheckAuth。
- if (path == "/debug" && (method == "GET" || method == "HEAD"))
- {
- HandleDebugPage(context, method == "HEAD");
- return;
- }
- if (!CheckAuth(context))
- {
- WriteJson(context, 401, BuildError(-4, "令牌校验失败,请在请求头 X-Access-Token 中携带有效令牌"));
- return;
- }
- if (path == "/api/com/invoke" && method == "POST")
- {
- await HandleInvokeAsync(context);
- }
- else if (path == "/api/com/open" && method == "POST")
- {
- await HandleConvenienceAsync(context, "open");
- }
- else if (path == "/api/com/close" && method == "POST")
- {
- await HandleConvenienceAsync(context, "close");
- }
- else if (path == "/api/card/read" && method == "POST")
- {
- await HandleCardReadAsync(context);
- }
- else if (path == "/api/scan/take" && method == "POST")
- {
- HandleScanTake(context);
- }
- else if (path == "/health" && method == "GET")
- {
- HandleHealth(context);
- }
- else if (path == "/admin/reinitialize" && method == "POST")
- {
- HandleReinitialize(context);
- }
- else if (path == "/admin/config" && method == "GET")
- {
- HandleConfig(context);
- }
- else
- {
- WriteJson(context, 404, BuildError(-4, "Not Found: " + path));
- }
- }
- catch (Exception ex)
- {
- Logger.Error("HTTP 处理异常", ex);
- try { WriteJson(context, 500, BuildError(-1, ex.Message)); }
- catch { }
- }
- }
- private async Task HandleInvokeAsync(HttpListenerContext context)
- {
- string body;
- try
- {
- body = ReadBody(context.Request);
- }
- catch (Exception ex)
- {
- WriteJson(context, 400, BuildError(-4, ex.Message));
- return;
- }
- if (string.IsNullOrWhiteSpace(body))
- {
- WriteJson(context, 400, BuildError(-4, "请求体为空"));
- return;
- }
- string func;
- string[] args;
- string progId;
- try
- {
- func = ExtractStringField(body, "func");
- args = ExtractStringArray(body, "args");
- progId = ExtractStringField(body, "progId"); // 可选:空=主组件
- }
- catch (Exception ex)
- {
- WriteJson(context, 400, BuildError(-4, "解析请求体失败: " + ex.Message));
- return;
- }
- if (string.IsNullOrWhiteSpace(func))
- {
- WriteJson(context, 400, BuildError(-4, "缺少 func 字段"));
- return;
- }
- // 调用计数、摘要日志与原文日志统一在 GatewayHost.ExecuteAsync 内完成
- ComResult result = await GatewayHost.Instance.ExecuteAsync(func, args, progId).ConfigureAwait(false);
- WriteJson(context, 200, BuildResult(result));
- }
- private async Task HandleConvenienceAsync(HttpListenerContext context, string func)
- {
- ComResult result = await GatewayHost.Instance.ExecuteAsync(func, null).ConfigureAwait(false);
- WriteJson(context, 200, BuildResult(result));
- }
- /// <summary>
- /// POST /api/scan/take
- /// 取走「扫码预捕获」缓冲里的码(消费式:取走即清空,同一个码不会返回两次)。
- /// 返回 {"code":0,"message":"","data":{"hit":true,"value":"...","ageMs":85}}
- /// {"code":0,"message":"","data":{"hit":false,"value":"","ageMs":0}}
- /// 码内容是医保支付凭证:只回给调用方,绝不写日志、绝不落盘。
- /// </summary>
- private void HandleScanTake(HttpListenerContext context)
- {
- try
- {
- if (!AppConfig.ScanCaptureEnabled)
- {
- WriteJson(context, 200, BuildScanResult(false, null, 0));
- return;
- }
- string code;
- int ageMs;
- bool hit = ScanBuffer.TryTake(out code, out ageMs);
- if (hit)
- {
- // 只记长度与存活时长,绝不记内容
- Logger.Info("[扫码预捕获] 命中,长度=" + code.Length + ",捕获于 " + ageMs + "ms 前");
- }
- WriteJson(context, 200, BuildScanResult(hit, code, ageMs));
- }
- catch (Exception ex)
- {
- Logger.Error("[扫码预捕获] 取缓冲异常", ex);
- WriteJson(context, 500, BuildError(-1, ex.Message));
- }
- }
- private static string BuildScanResult(bool hit, string value, int ageMs)
- {
- if (!hit || string.IsNullOrEmpty(value))
- {
- return "{\"code\":0,\"message\":\"\",\"data\":{\"hit\":false,\"value\":\"\",\"ageMs\":0}}";
- }
- return "{\"code\":0,\"message\":\"\",\"data\":{\"hit\":true,\"value\":" + Escape(value)
- + ",\"ageMs\":" + ageMs + "}}";
- }
- private async Task HandleCardReadAsync(HttpListenerContext context)
- {
- string body;
- try
- {
- body = ReadBody(context.Request);
- }
- catch (Exception ex)
- {
- WriteJson(context, 400, BuildError(-4, ex.Message));
- return;
- }
- if (string.IsNullOrWhiteSpace(body))
- {
- WriteJson(context, 400, BuildError(-4, "请求体为空"));
- return;
- }
- string payload;
- string input;
- string session;
- string cardClass;
- try
- {
- // payload 为已包装好的完整报文,优先;否则用 input(内层 XML)按 GetinPar 包装
- payload = ExtractStringField(body, "payload");
- input = ExtractStringField(body, "input");
- // 可选:会话策略(perRead 默认 / keepOpen,随本次请求走)
- session = ExtractStringField(body, "session");
- // 可选:调用方指定人员类别(1 本市 / 2 异地),传了则跳过 GetPersonClass
- cardClass = ExtractStringField(body, "card_class");
- }
- catch (Exception ex)
- {
- WriteJson(context, 400, BuildError(-4, "解析请求体失败: " + ex.Message));
- return;
- }
- if (string.IsNullOrWhiteSpace(payload) && !string.IsNullOrWhiteSpace(input))
- {
- // 防御:HIS 侧若误把"已包装"的报文当作 input 传来(含 <root 或 <?xml 声明),
- // 此处不再二次包装,否则会形成非法嵌套 XML(中心报 9020「无效的 xml 声明」,并导致人员类别误判)
- bool alreadyWrapped = input.IndexOf("<root", StringComparison.OrdinalIgnoreCase) >= 0
- || input.IndexOf("<?xml", StringComparison.OrdinalIgnoreCase) >= 0;
- payload = alreadyWrapped ? input : CardReaderFlow.WrapInput(input);
- }
- if (string.IsNullOrWhiteSpace(payload))
- {
- WriteJson(context, 400, BuildError(-4,
- "读卡入参为空:需提供 input(内层 XML)或 payload(完整 XML)"));
- return;
- }
- // 会话策略:keepOpen = 本次序列结束后不空闲关会话(仅测试用);默认 perRead = 用完即关。
- // Round49:改为随请求传参,不再调 SetSessionKeepOpen —— 那个是网关级开关,
- // 一旦设置就会粘住(异常时不复位),会连累 /api/com/invoke 等其它入口。
- bool keepOpen = string.Equals(session, "keepOpen", StringComparison.OrdinalIgnoreCase);
- CardReadResult result = await CardReaderFlow.ReadAsync(payload, cardClass, keepOpen).ConfigureAwait(false);
- WriteJson(context, 200, BuildCardResult(result, keepOpen ? "keepOpen" : "perRead"));
- }
- /// <summary>
- /// 输出 HTML 调试页(Doc\prototype\Round42-诊断面板调用测试-新布局.html 的发布副本)。
- /// 读取顺序:磁盘 Html\com-debug.html → 内嵌资源。磁盘优先是为了现场可直接改页面,
- /// 改完刷新浏览器即生效;内嵌兜底是为了部署时漏拷 Html 目录也不会 404。
- /// </summary>
- private void HandleDebugPage(HttpListenerContext context, bool headOnly)
- {
- string html = LoadDebugPage();
- if (html == null)
- {
- WriteJson(context, 500, BuildError(-1,
- "调试页未找到:程序目录缺少 Html\\com-debug.html,且未内嵌该资源"));
- return;
- }
- byte[] bytes = Encoding.UTF8.GetBytes(html);
- context.Response.StatusCode = 200;
- context.Response.ContentType = "text/html; charset=utf-8";
- context.Response.ContentLength64 = bytes.Length;
- AddCors(context.Response);
- if (!headOnly)
- {
- context.Response.OutputStream.Write(bytes, 0, bytes.Length);
- }
- context.Response.Close();
- }
- private string LoadDebugPage()
- {
- // 1) 磁盘优先:现场可改,改完刷新即生效
- try
- {
- string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Html", "com-debug.html");
- if (File.Exists(path))
- {
- return File.ReadAllText(path, Encoding.UTF8);
- }
- }
- catch (Exception ex)
- {
- Logger.Error("读取 Html\\com-debug.html 失败", ex);
- }
- // 2) 回退内嵌资源
- try
- {
- var assembly = typeof(HttpProtocol).Assembly;
- using (var stream = assembly.GetManifestResourceStream(DebugPageResource))
- {
- if (stream != null)
- {
- using (var reader = new StreamReader(stream, Encoding.UTF8))
- {
- return reader.ReadToEnd();
- }
- }
- }
- }
- catch (Exception ex)
- {
- Logger.Error("读取内嵌调试页资源失败", ex);
- }
- return null;
- }
- private void HandleHealth(HttpListenerContext context)
- {
- var host = GatewayHost.Instance;
- string json = "{"
- + "\"service\":\"BeiJingComService\","
- + "\"listen\":" + (IsListening ? "true" : "false") + ","
- + "\"httpPort\":" + _port + ","
- + "\"scanHook\":" + (BeiJingComService.WinForms.ScanWatcher.IsRunning ? "true" : "false") + ","
- + "\"dialogTopmost\":" + (DialogTopmostWatcher.IsHookInstalled ? "true" : "false") + ","
- + "\"dialogTopmostHits\":" + DialogTopmostWatcher.TopmostAppliedCount + ","
- + "\"dialogTopmostInCall\":" + (DialogTopmostWatcher.IsCallInFlight ? "true" : "false") + ","
- + "\"gateway\":{"
- + "\"initialized\":" + (host.IsInitialized ? "true" : "false") + ","
- + "\"faulted\":" + (host.IsFaulted ? "true" : "false") + ","
- + "\"pendingCount\":" + host.PendingCount + ","
- + "\"progId\":" + Escape(host.ProgId) + ","
- + "\"progIdSecondary\":" + Escape(host.ProgIdSecondary) + ","
- + "\"secondaryInitialized\":" + (host.IsSecondaryInitialized ? "true" : "false") + ","
- + "\"lastError\":" + Escape(host.LastError)
- + "},"
- + "\"invokeCount\":" + host.InvokeCount + ","
- + "\"lastInvokeTime\":" + Escape(host.LastInvokeTime.HasValue ? host.LastInvokeTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "") + ","
- + "\"lastElapsedMs\":" + host.LastElapsedMs
- + "}";
- WriteJson(context, 200, json);
- }
- private void HandleReinitialize(HttpListenerContext context)
- {
- try
- {
- GatewayHost.Instance.Reinitialize();
- WriteJson(context, 200, "{\"code\":0,\"message\":\"网关已重建\",\"elapsedMs\":0,\"output\":null}");
- }
- catch (Exception ex)
- {
- Logger.Error("重建网关失败", ex);
- WriteJson(context, 500, BuildError(-1, ex.Message));
- }
- }
- private void HandleConfig(HttpListenerContext context)
- {
- string json = "{"
- + "\"httpPort\":" + AppConfig.HttpPort + ","
- + "\"maxRequestSize\":" + AppConfig.MaxRequestSize + ","
- + "\"accessTokenSet\":" + (string.IsNullOrEmpty(AppConfig.AccessToken) ? "false" : "true") + ","
- + "\"corsAllowOrigin\":" + Escape(AppConfig.CorsAllowOrigin) + ","
- + "\"comProgId\":" + Escape(AppConfig.ComProgId) + ","
- + "\"comProgIdSecondary\":" + Escape(AppConfig.ComProgIdSecondary) + ","
- + "\"comTimeoutMs\":" + AppConfig.ComTimeoutMs + ","
- + "\"comIdleTimeoutMs\":" + AppConfig.ComIdleTimeoutMs + ","
- + "\"logDirectory\":" + Escape(AppConfig.LogDirectory)
- + "}";
- WriteJson(context, 200, json);
- }
- private string ReadBody(HttpListenerRequest request)
- {
- long max = AppConfig.MaxRequestSize;
- using (var memory = new MemoryStream())
- {
- byte[] buffer = new byte[8192];
- int read;
- while ((read = request.InputStream.Read(buffer, 0, buffer.Length)) > 0)
- {
- if (memory.Length + read > max)
- {
- throw new InvalidOperationException($"请求体超出大小限制({max} 字节)");
- }
- memory.Write(buffer, 0, read);
- }
- return Encoding.UTF8.GetString(memory.ToArray());
- }
- }
- private bool CheckAuth(HttpListenerContext context)
- {
- string expected = AppConfig.AccessToken;
- if (string.IsNullOrEmpty(expected)) return true;
- string provided = context.Request.Headers["X-Access-Token"];
- return string.Equals(provided, expected, StringComparison.Ordinal);
- }
- private void WriteJson(HttpListenerContext context, int statusCode, string json)
- {
- byte[] bytes = Encoding.UTF8.GetBytes(json ?? string.Empty);
- context.Response.StatusCode = statusCode;
- context.Response.ContentType = "application/json; charset=utf-8";
- context.Response.ContentLength64 = bytes.Length;
- AddCors(context.Response);
- if (bytes.Length > 0)
- {
- context.Response.OutputStream.Write(bytes, 0, bytes.Length);
- }
- context.Response.Close();
- }
- private void AddCors(HttpListenerResponse response)
- {
- string origin = AppConfig.CorsAllowOrigin;
- if (string.IsNullOrEmpty(origin)) return;
- response.Headers["Access-Control-Allow-Origin"] = origin;
- response.Headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS";
- response.Headers["Access-Control-Allow-Headers"] = "Content-Type, X-Access-Token";
- response.Headers["Access-Control-Max-Age"] = "86400";
- }
- private static string BuildResult(ComResult result)
- {
- return "{\"code\":" + result.Code
- + ",\"message\":" + Escape(result.Message)
- + ",\"elapsedMs\":" + result.ElapsedMs
- + ",\"output\":" + (result.Output == null ? "null" : Escape(result.Output))
- + "}";
- }
- private static string BuildCardResult(CardReadResult result, string sessionMode)
- {
- var builder = new StringBuilder();
- builder.Append("{\"code\":").Append(result.Code);
- builder.Append(",\"message\":").Append(Escape(result.Message));
- builder.Append(",\"elapsedMs\":").Append(result.ElapsedMs);
- builder.Append(",\"cardClass\":").Append(Escape(result.CardClass));
- builder.Append(",\"funcName\":").Append(Escape(result.FuncName));
- builder.Append(",\"cardNo\":").Append(Escape(result.CardNo));
- builder.Append(",\"sessionMode\":").Append(Escape(sessionMode));
- builder.Append(",\"output\":").Append(result.Output == null ? "null" : Escape(result.Output));
- builder.Append(",\"steps\":[");
- if (result.Steps != null)
- {
- for (int i = 0; i < result.Steps.Length; i++)
- {
- CardReadStep step = result.Steps[i];
- if (i > 0) builder.Append(',');
- builder.Append("{\"func\":").Append(Escape(step.Func));
- builder.Append(",\"code\":").Append(step.Code);
- builder.Append(",\"message\":").Append(Escape(step.Message));
- builder.Append(",\"elapsedMs\":").Append(step.ElapsedMs);
- builder.Append(",\"output\":").Append(step.Output == null ? "null" : Escape(step.Output));
- builder.Append('}');
- }
- }
- builder.Append("]}");
- return builder.ToString();
- }
- private static string BuildError(int code, string message)
- {
- return "{\"code\":" + code + ",\"message\":" + Escape(message) + ",\"elapsedMs\":0,\"output\":null}";
- }
- private static string Escape(string value)
- {
- if (value == null) return "null";
- var builder = new StringBuilder(value.Length + 16);
- builder.Append('"');
- foreach (char c in value)
- {
- switch (c)
- {
- case '"': builder.Append("\\\""); break;
- case '\\': builder.Append("\\\\"); break;
- case '\b': builder.Append("\\b"); break;
- case '\f': builder.Append("\\f"); break;
- case '\n': builder.Append("\\n"); break;
- case '\r': builder.Append("\\r"); break;
- case '\t': builder.Append("\\t"); break;
- default:
- if (c < 0x20)
- {
- builder.Append("\\u").Append(((int)c).ToString("x4", CultureInfo.InvariantCulture));
- }
- else
- {
- builder.Append(c);
- }
- break;
- }
- }
- builder.Append('"');
- return builder.ToString();
- }
- // -------- 极简 JSON 取值:只处理一级简单字段,够用且不引依赖 --------
- /// <summary>取一级字符串字段,形如 "func":"value"。找不到返回 null。</summary>
- private static string ExtractStringField(string json, string field)
- {
- if (string.IsNullOrEmpty(json)) return null;
- string key = "\"" + field + "\"";
- int keyIndex = json.IndexOf(key, StringComparison.Ordinal);
- if (keyIndex < 0) return null;
- int colon = json.IndexOf(':', keyIndex + key.Length);
- if (colon < 0) return null;
- int i = colon + 1;
- while (i < json.Length && char.IsWhiteSpace(json[i])) i++;
- if (i >= json.Length || json[i] != '"') return null;
- i++;
- var builder = new StringBuilder();
- while (i < json.Length)
- {
- char c = json[i];
- if (c == '"') break;
- if (c == '\\' && i + 1 < json.Length)
- {
- char next = json[i + 1];
- switch (next)
- {
- case '"': builder.Append('"'); break;
- case '\\': builder.Append('\\'); break;
- case '/': builder.Append('/'); break;
- case 'b': builder.Append('\b'); break;
- case 'f': builder.Append('\f'); break;
- case 'n': builder.Append('\n'); break;
- case 'r': builder.Append('\r'); break;
- case 't': builder.Append('\t'); break;
- default: builder.Append(next); break;
- }
- i += 2;
- continue;
- }
- builder.Append(c);
- i++;
- }
- return builder.ToString();
- }
- /// <summary>
- /// 取一级字符串数组字段,形如 "args":["a","b"]。
- /// 字段不存在时返回 null(表示无参);存在但为空数组时返回空数组。
- /// </summary>
- private static string[] ExtractStringArray(string json, string field)
- {
- if (string.IsNullOrEmpty(json)) return null;
- string key = "\"" + field + "\"";
- int keyIndex = json.IndexOf(key, StringComparison.Ordinal);
- if (keyIndex < 0) return null;
- int colon = json.IndexOf(':', keyIndex + key.Length);
- if (colon < 0) return null;
- int i = colon + 1;
- while (i < json.Length && char.IsWhiteSpace(json[i])) i++;
- if (i >= json.Length || json[i] != '[') return null;
- i++;
- var items = new System.Collections.Generic.List<string>();
- while (i < json.Length)
- {
- while (i < json.Length && (char.IsWhiteSpace(json[i]) || json[i] == ',')) i++;
- if (i >= json.Length || json[i] == ']') break;
- if (json[i] != '"') throw new FormatException("args 数组元素必须是字符串");
- i++;
- var builder = new StringBuilder();
- while (i < json.Length)
- {
- char c = json[i];
- if (c == '"') break;
- if (c == '\\' && i + 1 < json.Length)
- {
- char next = json[i + 1];
- switch (next)
- {
- case '"': builder.Append('"'); break;
- case '\\': builder.Append('\\'); break;
- case '/': builder.Append('/'); break;
- case 'b': builder.Append('\b'); break;
- case 'f': builder.Append('\f'); break;
- case 'n': builder.Append('\n'); break;
- case 'r': builder.Append('\r'); break;
- case 't': builder.Append('\t'); break;
- default: builder.Append(next); break;
- }
- i += 2;
- continue;
- }
- builder.Append(c);
- i++;
- }
- items.Add(builder.ToString());
- i++;
- }
- return items.ToArray();
- }
- public void Dispose()
- {
- Stop();
- try { if (_cts != null) _cts.Dispose(); }
- catch { }
- try { if (_listener != null) _listener.Close(); }
- catch { }
- }
- }
- }
|