HttpProtocol.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. using System;
  2. using System.Globalization;
  3. using System.IO;
  4. using System.Net;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using BeiJingComService.Core;
  9. using BeiJingComService.Infrastructure;
  10. namespace BeiJingComService.Protocols
  11. {
  12. /// <summary>
  13. /// HTTP 通道(本机 127.0.0.1)。
  14. /// 端点:
  15. /// POST /api/com/invoke 通用调用,body {"func":"...","args":["..."]}
  16. /// 返回 {"code","message","elapsedMs","output"}
  17. /// POST /api/com/open 便捷端点,等价于调用 COM 的 open
  18. /// POST /api/com/close 便捷端点,等价于调用 COM 的 close
  19. /// POST /api/card/read 读卡:服务端封装 open→GetPersonClass_Multimedia
  20. /// →GetPersonInfo(Nation)_Multimedia。
  21. /// body {"input":"<内层XML>"} 或 {"payload":"<完整XML>"}
  22. /// 可选 {"card_class":"1|2"}:调用方已知人员类别时传入,
  23. /// 传了则跳过 GetPersonClass_Multimedia,直接调参保信息
  24. /// 可选 {"session":"perRead|keepOpen"}:perRead(默认)用完即关;
  25. /// keepOpen 本次读卡序列不空闲关会话(只 Open 一次,测试用)。
  26. /// 该标志随本次请求走,不会残留影响其它入口。
  27. /// 返回体含 cardClass / funcName / cardNo / sessionMode
  28. /// (Round49 起不再有 cacheHit,服务端不设本地缓存)
  29. /// POST /api/scan/take 取走「扫码预捕获」缓冲里的码(Round54)。
  30. /// 消费式:取走即清空;超过 ScanCaptureTtlMs 视为过期未命中。
  31. /// 返回 {"code":0,"data":{"hit":bool,"value":"...","ageMs":n}}
  32. /// 码是医保支付凭证,服务端只回给调用方,不写日志不落盘
  33. /// GET /health 健康状态(真实网关状态,非硬编码)
  34. /// GET /debug HTML 调试页(托盘「HTML 调试」入口打开,与接口同源,
  35. /// 规避 file:// → 127.0.0.1 的 Private Network Access 拦截)
  36. /// POST /admin/reinitialize 重建网关(COM 实例、工作线程)
  37. /// GET /admin/config 当前配置(令牌不回显)
  38. /// 支持 CORS 与 OPTIONS 预检,便于浏览器/Cef/WebView2 前端直接调用。
  39. /// </summary>
  40. public class HttpProtocol : ITransportProtocol
  41. {
  42. /// <summary>内嵌调试页资源名:RootNamespace + 目录 + 文件名</summary>
  43. private const string DebugPageResource = "BeiJingComService.Html.com-debug.html";
  44. private readonly int _port;
  45. private HttpListener _listener;
  46. private CancellationTokenSource _cts;
  47. private Task _listenerTask;
  48. public string Name
  49. {
  50. get { return "Http"; }
  51. }
  52. public int Port
  53. {
  54. get { return _port; }
  55. }
  56. public bool IsListening
  57. {
  58. get { return _listener != null && _listener.IsListening; }
  59. }
  60. public HttpProtocol(int port)
  61. {
  62. _port = port;
  63. }
  64. public void Start()
  65. {
  66. _listener = new HttpListener();
  67. _listener.Prefixes.Add($"http://127.0.0.1:{_port}/");
  68. _listener.Start();
  69. _cts = new CancellationTokenSource();
  70. _listenerTask = Task.Run(() => ListenLoop(_cts.Token));
  71. Logger.Info($"HTTP 协议已启动: http://127.0.0.1:{_port}/");
  72. }
  73. public void Stop()
  74. {
  75. try { if (_cts != null) _cts.Cancel(); }
  76. catch { }
  77. try { if (_listener != null) _listener.Stop(); }
  78. catch (Exception ex) { Logger.Error("停止 HTTP 监听异常", ex); }
  79. try { if (_listenerTask != null) _listenerTask.Wait(TimeSpan.FromSeconds(2)); }
  80. catch { }
  81. Logger.Info("HTTP 协议已停止");
  82. }
  83. private async Task ListenLoop(CancellationToken token)
  84. {
  85. while (_listener != null && _listener.IsListening && !token.IsCancellationRequested)
  86. {
  87. try
  88. {
  89. HttpListenerContext context = await _listener.GetContextAsync();
  90. var ignored = Task.Run(() => HandleContextAsync(context));
  91. }
  92. catch (HttpListenerException) { break; }
  93. catch (OperationCanceledException) { break; }
  94. catch (ObjectDisposedException) { break; }
  95. catch (Exception ex) { Logger.Error("HTTP 监听异常", ex); }
  96. }
  97. }
  98. private async Task HandleContextAsync(HttpListenerContext context)
  99. {
  100. try
  101. {
  102. string path = context.Request.Url.AbsolutePath.ToLowerInvariant().TrimEnd('/');
  103. string method = context.Request.HttpMethod.ToUpperInvariant();
  104. if (method == "OPTIONS")
  105. {
  106. WriteJson(context, 204, "");
  107. return;
  108. }
  109. // 调试页放在令牌校验之前:它是静态 HTML,不含任何业务数据;
  110. // 若放在后面,一旦 AccessToken 非空,页面本身就打不开、也无法输入令牌自救。
  111. // 页面内发起的 /api/com/invoke 等接口调用,仍然走下面的 CheckAuth。
  112. if (path == "/debug" && (method == "GET" || method == "HEAD"))
  113. {
  114. HandleDebugPage(context, method == "HEAD");
  115. return;
  116. }
  117. if (!CheckAuth(context))
  118. {
  119. WriteJson(context, 401, BuildError(-4, "令牌校验失败,请在请求头 X-Access-Token 中携带有效令牌"));
  120. return;
  121. }
  122. if (path == "/api/com/invoke" && method == "POST")
  123. {
  124. await HandleInvokeAsync(context);
  125. }
  126. else if (path == "/api/com/open" && method == "POST")
  127. {
  128. await HandleConvenienceAsync(context, "open");
  129. }
  130. else if (path == "/api/com/close" && method == "POST")
  131. {
  132. await HandleConvenienceAsync(context, "close");
  133. }
  134. else if (path == "/api/card/read" && method == "POST")
  135. {
  136. await HandleCardReadAsync(context);
  137. }
  138. else if (path == "/api/scan/take" && method == "POST")
  139. {
  140. HandleScanTake(context);
  141. }
  142. else if (path == "/health" && method == "GET")
  143. {
  144. HandleHealth(context);
  145. }
  146. else if (path == "/admin/reinitialize" && method == "POST")
  147. {
  148. HandleReinitialize(context);
  149. }
  150. else if (path == "/admin/config" && method == "GET")
  151. {
  152. HandleConfig(context);
  153. }
  154. else
  155. {
  156. WriteJson(context, 404, BuildError(-4, "Not Found: " + path));
  157. }
  158. }
  159. catch (Exception ex)
  160. {
  161. Logger.Error("HTTP 处理异常", ex);
  162. try { WriteJson(context, 500, BuildError(-1, ex.Message)); }
  163. catch { }
  164. }
  165. }
  166. private async Task HandleInvokeAsync(HttpListenerContext context)
  167. {
  168. string body;
  169. try
  170. {
  171. body = ReadBody(context.Request);
  172. }
  173. catch (Exception ex)
  174. {
  175. WriteJson(context, 400, BuildError(-4, ex.Message));
  176. return;
  177. }
  178. if (string.IsNullOrWhiteSpace(body))
  179. {
  180. WriteJson(context, 400, BuildError(-4, "请求体为空"));
  181. return;
  182. }
  183. string func;
  184. string[] args;
  185. string progId;
  186. try
  187. {
  188. func = ExtractStringField(body, "func");
  189. args = ExtractStringArray(body, "args");
  190. progId = ExtractStringField(body, "progId"); // 可选:空=主组件
  191. }
  192. catch (Exception ex)
  193. {
  194. WriteJson(context, 400, BuildError(-4, "解析请求体失败: " + ex.Message));
  195. return;
  196. }
  197. if (string.IsNullOrWhiteSpace(func))
  198. {
  199. WriteJson(context, 400, BuildError(-4, "缺少 func 字段"));
  200. return;
  201. }
  202. // 调用计数、摘要日志与原文日志统一在 GatewayHost.ExecuteAsync 内完成
  203. ComResult result = await GatewayHost.Instance.ExecuteAsync(func, args, progId).ConfigureAwait(false);
  204. WriteJson(context, 200, BuildResult(result));
  205. }
  206. private async Task HandleConvenienceAsync(HttpListenerContext context, string func)
  207. {
  208. ComResult result = await GatewayHost.Instance.ExecuteAsync(func, null).ConfigureAwait(false);
  209. WriteJson(context, 200, BuildResult(result));
  210. }
  211. /// <summary>
  212. /// POST /api/scan/take
  213. /// 取走「扫码预捕获」缓冲里的码(消费式:取走即清空,同一个码不会返回两次)。
  214. /// 返回 {"code":0,"message":"","data":{"hit":true,"value":"...","ageMs":85}}
  215. /// {"code":0,"message":"","data":{"hit":false,"value":"","ageMs":0}}
  216. /// 码内容是医保支付凭证:只回给调用方,绝不写日志、绝不落盘。
  217. /// </summary>
  218. private void HandleScanTake(HttpListenerContext context)
  219. {
  220. try
  221. {
  222. if (!AppConfig.ScanCaptureEnabled)
  223. {
  224. WriteJson(context, 200, BuildScanResult(false, null, 0));
  225. return;
  226. }
  227. string code;
  228. int ageMs;
  229. bool hit = ScanBuffer.TryTake(out code, out ageMs);
  230. if (hit)
  231. {
  232. // 只记长度与存活时长,绝不记内容
  233. Logger.Info("[扫码预捕获] 命中,长度=" + code.Length + ",捕获于 " + ageMs + "ms 前");
  234. }
  235. WriteJson(context, 200, BuildScanResult(hit, code, ageMs));
  236. }
  237. catch (Exception ex)
  238. {
  239. Logger.Error("[扫码预捕获] 取缓冲异常", ex);
  240. WriteJson(context, 500, BuildError(-1, ex.Message));
  241. }
  242. }
  243. private static string BuildScanResult(bool hit, string value, int ageMs)
  244. {
  245. if (!hit || string.IsNullOrEmpty(value))
  246. {
  247. return "{\"code\":0,\"message\":\"\",\"data\":{\"hit\":false,\"value\":\"\",\"ageMs\":0}}";
  248. }
  249. return "{\"code\":0,\"message\":\"\",\"data\":{\"hit\":true,\"value\":" + Escape(value)
  250. + ",\"ageMs\":" + ageMs + "}}";
  251. }
  252. private async Task HandleCardReadAsync(HttpListenerContext context)
  253. {
  254. string body;
  255. try
  256. {
  257. body = ReadBody(context.Request);
  258. }
  259. catch (Exception ex)
  260. {
  261. WriteJson(context, 400, BuildError(-4, ex.Message));
  262. return;
  263. }
  264. if (string.IsNullOrWhiteSpace(body))
  265. {
  266. WriteJson(context, 400, BuildError(-4, "请求体为空"));
  267. return;
  268. }
  269. string payload;
  270. string input;
  271. string session;
  272. string cardClass;
  273. try
  274. {
  275. // payload 为已包装好的完整报文,优先;否则用 input(内层 XML)按 GetinPar 包装
  276. payload = ExtractStringField(body, "payload");
  277. input = ExtractStringField(body, "input");
  278. // 可选:会话策略(perRead 默认 / keepOpen,随本次请求走)
  279. session = ExtractStringField(body, "session");
  280. // 可选:调用方指定人员类别(1 本市 / 2 异地),传了则跳过 GetPersonClass
  281. cardClass = ExtractStringField(body, "card_class");
  282. }
  283. catch (Exception ex)
  284. {
  285. WriteJson(context, 400, BuildError(-4, "解析请求体失败: " + ex.Message));
  286. return;
  287. }
  288. if (string.IsNullOrWhiteSpace(payload) && !string.IsNullOrWhiteSpace(input))
  289. {
  290. // 防御:HIS 侧若误把"已包装"的报文当作 input 传来(含 <root 或 <?xml 声明),
  291. // 此处不再二次包装,否则会形成非法嵌套 XML(中心报 9020「无效的 xml 声明」,并导致人员类别误判)
  292. bool alreadyWrapped = input.IndexOf("<root", StringComparison.OrdinalIgnoreCase) >= 0
  293. || input.IndexOf("<?xml", StringComparison.OrdinalIgnoreCase) >= 0;
  294. payload = alreadyWrapped ? input : CardReaderFlow.WrapInput(input);
  295. }
  296. if (string.IsNullOrWhiteSpace(payload))
  297. {
  298. WriteJson(context, 400, BuildError(-4,
  299. "读卡入参为空:需提供 input(内层 XML)或 payload(完整 XML)"));
  300. return;
  301. }
  302. // 会话策略:keepOpen = 本次序列结束后不空闲关会话(仅测试用);默认 perRead = 用完即关。
  303. // Round49:改为随请求传参,不再调 SetSessionKeepOpen —— 那个是网关级开关,
  304. // 一旦设置就会粘住(异常时不复位),会连累 /api/com/invoke 等其它入口。
  305. bool keepOpen = string.Equals(session, "keepOpen", StringComparison.OrdinalIgnoreCase);
  306. CardReadResult result = await CardReaderFlow.ReadAsync(payload, cardClass, keepOpen).ConfigureAwait(false);
  307. WriteJson(context, 200, BuildCardResult(result, keepOpen ? "keepOpen" : "perRead"));
  308. }
  309. /// <summary>
  310. /// 输出 HTML 调试页(Doc\prototype\Round42-诊断面板调用测试-新布局.html 的发布副本)。
  311. /// 读取顺序:磁盘 Html\com-debug.html → 内嵌资源。磁盘优先是为了现场可直接改页面,
  312. /// 改完刷新浏览器即生效;内嵌兜底是为了部署时漏拷 Html 目录也不会 404。
  313. /// </summary>
  314. private void HandleDebugPage(HttpListenerContext context, bool headOnly)
  315. {
  316. string html = LoadDebugPage();
  317. if (html == null)
  318. {
  319. WriteJson(context, 500, BuildError(-1,
  320. "调试页未找到:程序目录缺少 Html\\com-debug.html,且未内嵌该资源"));
  321. return;
  322. }
  323. byte[] bytes = Encoding.UTF8.GetBytes(html);
  324. context.Response.StatusCode = 200;
  325. context.Response.ContentType = "text/html; charset=utf-8";
  326. context.Response.ContentLength64 = bytes.Length;
  327. AddCors(context.Response);
  328. if (!headOnly)
  329. {
  330. context.Response.OutputStream.Write(bytes, 0, bytes.Length);
  331. }
  332. context.Response.Close();
  333. }
  334. private string LoadDebugPage()
  335. {
  336. // 1) 磁盘优先:现场可改,改完刷新即生效
  337. try
  338. {
  339. string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Html", "com-debug.html");
  340. if (File.Exists(path))
  341. {
  342. return File.ReadAllText(path, Encoding.UTF8);
  343. }
  344. }
  345. catch (Exception ex)
  346. {
  347. Logger.Error("读取 Html\\com-debug.html 失败", ex);
  348. }
  349. // 2) 回退内嵌资源
  350. try
  351. {
  352. var assembly = typeof(HttpProtocol).Assembly;
  353. using (var stream = assembly.GetManifestResourceStream(DebugPageResource))
  354. {
  355. if (stream != null)
  356. {
  357. using (var reader = new StreamReader(stream, Encoding.UTF8))
  358. {
  359. return reader.ReadToEnd();
  360. }
  361. }
  362. }
  363. }
  364. catch (Exception ex)
  365. {
  366. Logger.Error("读取内嵌调试页资源失败", ex);
  367. }
  368. return null;
  369. }
  370. private void HandleHealth(HttpListenerContext context)
  371. {
  372. var host = GatewayHost.Instance;
  373. string json = "{"
  374. + "\"service\":\"BeiJingComService\","
  375. + "\"listen\":" + (IsListening ? "true" : "false") + ","
  376. + "\"httpPort\":" + _port + ","
  377. + "\"scanHook\":" + (BeiJingComService.WinForms.ScanWatcher.IsRunning ? "true" : "false") + ","
  378. + "\"dialogTopmost\":" + (DialogTopmostWatcher.IsHookInstalled ? "true" : "false") + ","
  379. + "\"dialogTopmostHits\":" + DialogTopmostWatcher.TopmostAppliedCount + ","
  380. + "\"dialogTopmostInCall\":" + (DialogTopmostWatcher.IsCallInFlight ? "true" : "false") + ","
  381. + "\"gateway\":{"
  382. + "\"initialized\":" + (host.IsInitialized ? "true" : "false") + ","
  383. + "\"faulted\":" + (host.IsFaulted ? "true" : "false") + ","
  384. + "\"pendingCount\":" + host.PendingCount + ","
  385. + "\"progId\":" + Escape(host.ProgId) + ","
  386. + "\"progIdSecondary\":" + Escape(host.ProgIdSecondary) + ","
  387. + "\"secondaryInitialized\":" + (host.IsSecondaryInitialized ? "true" : "false") + ","
  388. + "\"lastError\":" + Escape(host.LastError)
  389. + "},"
  390. + "\"invokeCount\":" + host.InvokeCount + ","
  391. + "\"lastInvokeTime\":" + Escape(host.LastInvokeTime.HasValue ? host.LastInvokeTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "") + ","
  392. + "\"lastElapsedMs\":" + host.LastElapsedMs
  393. + "}";
  394. WriteJson(context, 200, json);
  395. }
  396. private void HandleReinitialize(HttpListenerContext context)
  397. {
  398. try
  399. {
  400. GatewayHost.Instance.Reinitialize();
  401. WriteJson(context, 200, "{\"code\":0,\"message\":\"网关已重建\",\"elapsedMs\":0,\"output\":null}");
  402. }
  403. catch (Exception ex)
  404. {
  405. Logger.Error("重建网关失败", ex);
  406. WriteJson(context, 500, BuildError(-1, ex.Message));
  407. }
  408. }
  409. private void HandleConfig(HttpListenerContext context)
  410. {
  411. string json = "{"
  412. + "\"httpPort\":" + AppConfig.HttpPort + ","
  413. + "\"maxRequestSize\":" + AppConfig.MaxRequestSize + ","
  414. + "\"accessTokenSet\":" + (string.IsNullOrEmpty(AppConfig.AccessToken) ? "false" : "true") + ","
  415. + "\"corsAllowOrigin\":" + Escape(AppConfig.CorsAllowOrigin) + ","
  416. + "\"comProgId\":" + Escape(AppConfig.ComProgId) + ","
  417. + "\"comProgIdSecondary\":" + Escape(AppConfig.ComProgIdSecondary) + ","
  418. + "\"comTimeoutMs\":" + AppConfig.ComTimeoutMs + ","
  419. + "\"comIdleTimeoutMs\":" + AppConfig.ComIdleTimeoutMs + ","
  420. + "\"logDirectory\":" + Escape(AppConfig.LogDirectory)
  421. + "}";
  422. WriteJson(context, 200, json);
  423. }
  424. private string ReadBody(HttpListenerRequest request)
  425. {
  426. long max = AppConfig.MaxRequestSize;
  427. using (var memory = new MemoryStream())
  428. {
  429. byte[] buffer = new byte[8192];
  430. int read;
  431. while ((read = request.InputStream.Read(buffer, 0, buffer.Length)) > 0)
  432. {
  433. if (memory.Length + read > max)
  434. {
  435. throw new InvalidOperationException($"请求体超出大小限制({max} 字节)");
  436. }
  437. memory.Write(buffer, 0, read);
  438. }
  439. return Encoding.UTF8.GetString(memory.ToArray());
  440. }
  441. }
  442. private bool CheckAuth(HttpListenerContext context)
  443. {
  444. string expected = AppConfig.AccessToken;
  445. if (string.IsNullOrEmpty(expected)) return true;
  446. string provided = context.Request.Headers["X-Access-Token"];
  447. return string.Equals(provided, expected, StringComparison.Ordinal);
  448. }
  449. private void WriteJson(HttpListenerContext context, int statusCode, string json)
  450. {
  451. byte[] bytes = Encoding.UTF8.GetBytes(json ?? string.Empty);
  452. context.Response.StatusCode = statusCode;
  453. context.Response.ContentType = "application/json; charset=utf-8";
  454. context.Response.ContentLength64 = bytes.Length;
  455. AddCors(context.Response);
  456. if (bytes.Length > 0)
  457. {
  458. context.Response.OutputStream.Write(bytes, 0, bytes.Length);
  459. }
  460. context.Response.Close();
  461. }
  462. private void AddCors(HttpListenerResponse response)
  463. {
  464. string origin = AppConfig.CorsAllowOrigin;
  465. if (string.IsNullOrEmpty(origin)) return;
  466. response.Headers["Access-Control-Allow-Origin"] = origin;
  467. response.Headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS";
  468. response.Headers["Access-Control-Allow-Headers"] = "Content-Type, X-Access-Token";
  469. response.Headers["Access-Control-Max-Age"] = "86400";
  470. }
  471. private static string BuildResult(ComResult result)
  472. {
  473. return "{\"code\":" + result.Code
  474. + ",\"message\":" + Escape(result.Message)
  475. + ",\"elapsedMs\":" + result.ElapsedMs
  476. + ",\"output\":" + (result.Output == null ? "null" : Escape(result.Output))
  477. + "}";
  478. }
  479. private static string BuildCardResult(CardReadResult result, string sessionMode)
  480. {
  481. var builder = new StringBuilder();
  482. builder.Append("{\"code\":").Append(result.Code);
  483. builder.Append(",\"message\":").Append(Escape(result.Message));
  484. builder.Append(",\"elapsedMs\":").Append(result.ElapsedMs);
  485. builder.Append(",\"cardClass\":").Append(Escape(result.CardClass));
  486. builder.Append(",\"funcName\":").Append(Escape(result.FuncName));
  487. builder.Append(",\"cardNo\":").Append(Escape(result.CardNo));
  488. builder.Append(",\"sessionMode\":").Append(Escape(sessionMode));
  489. builder.Append(",\"output\":").Append(result.Output == null ? "null" : Escape(result.Output));
  490. builder.Append(",\"steps\":[");
  491. if (result.Steps != null)
  492. {
  493. for (int i = 0; i < result.Steps.Length; i++)
  494. {
  495. CardReadStep step = result.Steps[i];
  496. if (i > 0) builder.Append(',');
  497. builder.Append("{\"func\":").Append(Escape(step.Func));
  498. builder.Append(",\"code\":").Append(step.Code);
  499. builder.Append(",\"message\":").Append(Escape(step.Message));
  500. builder.Append(",\"elapsedMs\":").Append(step.ElapsedMs);
  501. builder.Append(",\"output\":").Append(step.Output == null ? "null" : Escape(step.Output));
  502. builder.Append('}');
  503. }
  504. }
  505. builder.Append("]}");
  506. return builder.ToString();
  507. }
  508. private static string BuildError(int code, string message)
  509. {
  510. return "{\"code\":" + code + ",\"message\":" + Escape(message) + ",\"elapsedMs\":0,\"output\":null}";
  511. }
  512. private static string Escape(string value)
  513. {
  514. if (value == null) return "null";
  515. var builder = new StringBuilder(value.Length + 16);
  516. builder.Append('"');
  517. foreach (char c in value)
  518. {
  519. switch (c)
  520. {
  521. case '"': builder.Append("\\\""); break;
  522. case '\\': builder.Append("\\\\"); break;
  523. case '\b': builder.Append("\\b"); break;
  524. case '\f': builder.Append("\\f"); break;
  525. case '\n': builder.Append("\\n"); break;
  526. case '\r': builder.Append("\\r"); break;
  527. case '\t': builder.Append("\\t"); break;
  528. default:
  529. if (c < 0x20)
  530. {
  531. builder.Append("\\u").Append(((int)c).ToString("x4", CultureInfo.InvariantCulture));
  532. }
  533. else
  534. {
  535. builder.Append(c);
  536. }
  537. break;
  538. }
  539. }
  540. builder.Append('"');
  541. return builder.ToString();
  542. }
  543. // -------- 极简 JSON 取值:只处理一级简单字段,够用且不引依赖 --------
  544. /// <summary>取一级字符串字段,形如 "func":"value"。找不到返回 null。</summary>
  545. private static string ExtractStringField(string json, string field)
  546. {
  547. if (string.IsNullOrEmpty(json)) return null;
  548. string key = "\"" + field + "\"";
  549. int keyIndex = json.IndexOf(key, StringComparison.Ordinal);
  550. if (keyIndex < 0) return null;
  551. int colon = json.IndexOf(':', keyIndex + key.Length);
  552. if (colon < 0) return null;
  553. int i = colon + 1;
  554. while (i < json.Length && char.IsWhiteSpace(json[i])) i++;
  555. if (i >= json.Length || json[i] != '"') return null;
  556. i++;
  557. var builder = new StringBuilder();
  558. while (i < json.Length)
  559. {
  560. char c = json[i];
  561. if (c == '"') break;
  562. if (c == '\\' && i + 1 < json.Length)
  563. {
  564. char next = json[i + 1];
  565. switch (next)
  566. {
  567. case '"': builder.Append('"'); break;
  568. case '\\': builder.Append('\\'); break;
  569. case '/': builder.Append('/'); break;
  570. case 'b': builder.Append('\b'); break;
  571. case 'f': builder.Append('\f'); break;
  572. case 'n': builder.Append('\n'); break;
  573. case 'r': builder.Append('\r'); break;
  574. case 't': builder.Append('\t'); break;
  575. default: builder.Append(next); break;
  576. }
  577. i += 2;
  578. continue;
  579. }
  580. builder.Append(c);
  581. i++;
  582. }
  583. return builder.ToString();
  584. }
  585. /// <summary>
  586. /// 取一级字符串数组字段,形如 "args":["a","b"]。
  587. /// 字段不存在时返回 null(表示无参);存在但为空数组时返回空数组。
  588. /// </summary>
  589. private static string[] ExtractStringArray(string json, string field)
  590. {
  591. if (string.IsNullOrEmpty(json)) return null;
  592. string key = "\"" + field + "\"";
  593. int keyIndex = json.IndexOf(key, StringComparison.Ordinal);
  594. if (keyIndex < 0) return null;
  595. int colon = json.IndexOf(':', keyIndex + key.Length);
  596. if (colon < 0) return null;
  597. int i = colon + 1;
  598. while (i < json.Length && char.IsWhiteSpace(json[i])) i++;
  599. if (i >= json.Length || json[i] != '[') return null;
  600. i++;
  601. var items = new System.Collections.Generic.List<string>();
  602. while (i < json.Length)
  603. {
  604. while (i < json.Length && (char.IsWhiteSpace(json[i]) || json[i] == ',')) i++;
  605. if (i >= json.Length || json[i] == ']') break;
  606. if (json[i] != '"') throw new FormatException("args 数组元素必须是字符串");
  607. i++;
  608. var builder = new StringBuilder();
  609. while (i < json.Length)
  610. {
  611. char c = json[i];
  612. if (c == '"') break;
  613. if (c == '\\' && i + 1 < json.Length)
  614. {
  615. char next = json[i + 1];
  616. switch (next)
  617. {
  618. case '"': builder.Append('"'); break;
  619. case '\\': builder.Append('\\'); break;
  620. case '/': builder.Append('/'); break;
  621. case 'b': builder.Append('\b'); break;
  622. case 'f': builder.Append('\f'); break;
  623. case 'n': builder.Append('\n'); break;
  624. case 'r': builder.Append('\r'); break;
  625. case 't': builder.Append('\t'); break;
  626. default: builder.Append(next); break;
  627. }
  628. i += 2;
  629. continue;
  630. }
  631. builder.Append(c);
  632. i++;
  633. }
  634. items.Add(builder.ToString());
  635. i++;
  636. }
  637. return items.ToArray();
  638. }
  639. public void Dispose()
  640. {
  641. Stop();
  642. try { if (_cts != null) _cts.Dispose(); }
  643. catch { }
  644. try { if (_listener != null) _listener.Close(); }
  645. catch { }
  646. }
  647. }
  648. }