ComClient.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. using System.Text;
  5. namespace BeiJingComService.Client
  6. {
  7. /// <summary>
  8. /// HIS 侧本地 COM 通讯客户端。整个文件可原样拷贝到 HIS 工程使用,
  9. /// 只依赖 System / System.Net,不需要任何第三方库(无 Newtonsoft)。
  10. ///
  11. /// 替换关系:
  12. /// 旧:Business(inputData, ref outputData, ref pErrMsg) → 直接 P/Invoke DLL
  13. /// 新:Invoke(func, args, out outputData, out pErrMsg) → HTTP 调用本机 COM 服务
  14. ///
  15. /// 之所以把 COM 调用搬到独立进程,是为了:
  16. /// 1) COM 实例在服务进程内常驻复用(只在首次/空闲超时后 open),读卡不再慢;
  17. /// 2) HIS 进程只需发 HTTP,不加载也不依赖任何医保 COM/OCX 组件。
  18. ///
  19. /// 编码:HIS ←→ 服务为 UTF-8;COM 侧编码由服务进程内部处理,HIS 无需关心。
  20. /// </summary>
  21. public class ComClient
  22. {
  23. static ComClient()
  24. {
  25. // 关闭 100-Continue:否则每次 POST 都要多一个往返,读卡会明显变慢
  26. ServicePointManager.Expect100Continue = false;
  27. // 关闭 Nagle:报文一次发完,不要攒包
  28. ServicePointManager.UseNagleAlgorithm = false;
  29. // 多窗口并发时不被默认 2 连接限制卡住
  30. ServicePointManager.DefaultConnectionLimit = 64;
  31. ServicePointManager.CheckCertificateRevocationList = false;
  32. }
  33. /// <summary>服务地址,末尾不要带斜杠。</summary>
  34. public string BaseUrl { get; private set; }
  35. /// <summary>访问令牌,与服务 App.config 的 AccessToken 一致;服务留空则这里也留空。</summary>
  36. public string AccessToken { get; private set; }
  37. /// <summary>超时时间(毫秒)。必须大于服务的 ComTimeoutMs(默认 60000),建议 90000。</summary>
  38. public int TimeoutMs { get; private set; }
  39. public ComClient(string baseUrl = "http://127.0.0.1:5001", string accessToken = null, int timeoutMs = 90000)
  40. {
  41. BaseUrl = (baseUrl ?? "http://127.0.0.1:5001").TrimEnd('/');
  42. AccessToken = accessToken ?? string.Empty;
  43. TimeoutMs = timeoutMs > 0 ? timeoutMs : 90000;
  44. }
  45. // =====================================================================
  46. // 通用调用
  47. // =====================================================================
  48. /// <summary>
  49. /// 调用一个本地 COM 方法。
  50. /// </summary>
  51. /// <param name="func">COM 方法名,如 open / close / ReadCardObj / BussniessObj / Trade / TradeAll。</param>
  52. /// <param name="args">按顺序对应 COM 方法的各参数;为 null 或空表示无参(open/close 形态)。</param>
  53. /// <param name="outputData">成功时为 COM 方法最后一个参数的最终值;失败时为空串。</param>
  54. /// <param name="pErrMsg">错误信息;成功时为空串。</param>
  55. /// <returns>
  56. /// 0 调用成功
  57. /// -1 执行异常(COM 方法内部抛错)
  58. /// -2 调用超时(请求已提交至 COM,结果作废,严禁重复提交)
  59. /// -3 服务未初始化 / 已停止
  60. /// -4 请求报文为空或参数错误
  61. /// -5 无法连接服务(服务没启动 / 端口被改 / 被安全软件拦截)
  62. /// -6 令牌校验失败(HTTP 401)
  63. /// -7 服务返回了无法识别的结果
  64. /// </returns>
  65. public int Invoke(string func, string[] args, out string outputData, out string pErrMsg)
  66. {
  67. return Invoke(func, args, null, out outputData, out pErrMsg);
  68. }
  69. /// <summary>
  70. /// 调用指定 ProgID 的 COM 方法。progId 为空时使用服务的主组件(MedicareCom.Outpatient)。
  71. /// </summary>
  72. public int Invoke(string func, string[] args, string progId, out string outputData, out string pErrMsg)
  73. {
  74. outputData = string.Empty;
  75. pErrMsg = string.Empty;
  76. if (string.IsNullOrWhiteSpace(func))
  77. {
  78. pErrMsg = "入参 func 为空";
  79. return -4;
  80. }
  81. try
  82. {
  83. string body = BuildInvokeBody(func, args, progId);
  84. string responseText;
  85. int code = Post("/api/com/invoke", body, out responseText);
  86. if (code != 0)
  87. {
  88. pErrMsg = responseText;
  89. return code;
  90. }
  91. // 解服务包装:{"code":0,"message":"","elapsedMs":123,"output":"..."}
  92. int gatewayCode = ExtractIntField(responseText, "code");
  93. string message = ExtractStringField(responseText, "message");
  94. if (gatewayCode != 0)
  95. {
  96. pErrMsg = string.IsNullOrEmpty(message) ? ("服务返回码 " + gatewayCode) : message;
  97. return gatewayCode;
  98. }
  99. outputData = ExtractStringField(responseText, "output") ?? string.Empty;
  100. return 0;
  101. }
  102. catch (Exception ex)
  103. {
  104. pErrMsg = "调用(Invoke)异常:" + ex.Message;
  105. return -1;
  106. }
  107. }
  108. /// <summary>建立 COM 会话(等价于调用 COM 的 open)。一般无需手工调用,服务会按需自动 open。</summary>
  109. public int Open(out string outputData, out string pErrMsg)
  110. {
  111. return PostConvenience("/api/com/open", out outputData, out pErrMsg);
  112. }
  113. /// <summary>关闭 COM 会话(等价于调用 COM 的 close)。</summary>
  114. public int Close(out string outputData, out string pErrMsg)
  115. {
  116. return PostConvenience("/api/com/close", out outputData, out pErrMsg);
  117. }
  118. /// <summary>
  119. /// 读卡:服务端封装了 open → GetPersonClass_Multimedia → GetPersonInfo(Nation)_Multimedia。
  120. /// </summary>
  121. /// <param name="input">HIS 侧拼接的内层 XML(形如 &lt;multiclass&gt;...&lt;/multiclass&gt;...&lt;officeName&gt;...&lt;/officeName&gt;),
  122. /// 服务端负责按 GetinPar 包装成完整报文体。</param>
  123. /// <param name="cardClass">中心返回的人员类别:1 本市、2 异地;取不到时为空串。</param>
  124. /// <param name="outputData">成功时为最终参保信息返回 XML。</param>
  125. /// <param name="pErrMsg">错误信息;成功时为空串。</param>
  126. /// <returns>同 Invoke 的结果码约定(0 成功,-2 超时,-3 未就绪,-4 参数错误,-5 连不上,-6 令牌失败)。</returns>
  127. public int ReadCard(string input, out string cardClass, out string outputData, out string pErrMsg)
  128. {
  129. cardClass = string.Empty;
  130. outputData = string.Empty;
  131. pErrMsg = string.Empty;
  132. if (string.IsNullOrWhiteSpace(input))
  133. {
  134. pErrMsg = "读卡入参 input 为空";
  135. return -4;
  136. }
  137. try
  138. {
  139. string body = "{\"input\":" + Quote(input) + "}";
  140. string responseText;
  141. int code = Post("/api/card/read", body, out responseText);
  142. if (code != 0)
  143. {
  144. pErrMsg = responseText;
  145. return code;
  146. }
  147. int gatewayCode = ExtractIntField(responseText, "code");
  148. string message = ExtractStringField(responseText, "message");
  149. cardClass = ExtractStringField(responseText, "cardClass") ?? string.Empty;
  150. if (gatewayCode != 0)
  151. {
  152. pErrMsg = string.IsNullOrEmpty(message) ? ("服务返回码 " + gatewayCode) : message;
  153. return gatewayCode;
  154. }
  155. outputData = ExtractStringField(responseText, "output") ?? string.Empty;
  156. return 0;
  157. }
  158. catch (Exception ex)
  159. {
  160. pErrMsg = "读卡(ReadCard)异常:" + ex.Message;
  161. return -1;
  162. }
  163. }
  164. /// <summary>
  165. /// 探活。返回 false 时 status 里是原因,可直接提示给操作员。
  166. /// 建议 HIS 在登录/打开收费窗口时调一次,比等到读卡时才报错友好。
  167. /// </summary>
  168. public bool Ping(out string status)
  169. {
  170. try
  171. {
  172. string responseText;
  173. int code = Get("/health", out responseText);
  174. if (code != 0)
  175. {
  176. status = responseText;
  177. return false;
  178. }
  179. int gatewayCode = ExtractIntField(responseText, "code");
  180. if (gatewayCode == -6) { status = "令牌校验失败"; return false; }
  181. bool initialized = ExtractBoolField(responseText, "initialized");
  182. bool listening = ExtractBoolField(responseText, "listen");
  183. status = initialized && listening ? "正常" : "服务未就绪: " + responseText;
  184. return initialized && listening;
  185. }
  186. catch (Exception ex)
  187. {
  188. status = ex.Message;
  189. return false;
  190. }
  191. }
  192. /// <summary>重建网关(COM 实例、工作线程全部重建;进入故障态时使用)。</summary>
  193. public bool Reinitialize(out string message)
  194. {
  195. try
  196. {
  197. string responseText;
  198. int code = Post("/admin/reinitialize", string.Empty, out responseText);
  199. message = code == 0 ? "服务已重建" : responseText;
  200. return code == 0;
  201. }
  202. catch (Exception ex)
  203. {
  204. message = ex.Message;
  205. return false;
  206. }
  207. }
  208. // =====================================================================
  209. // 内部实现
  210. // =====================================================================
  211. private int PostConvenience(string path, out string outputData, out string pErrMsg)
  212. {
  213. outputData = string.Empty;
  214. pErrMsg = string.Empty;
  215. try
  216. {
  217. string responseText;
  218. int code = Post(path, string.Empty, out responseText);
  219. if (code != 0)
  220. {
  221. pErrMsg = responseText;
  222. return code;
  223. }
  224. int gatewayCode = ExtractIntField(responseText, "code");
  225. string message = ExtractStringField(responseText, "message");
  226. if (gatewayCode != 0)
  227. {
  228. pErrMsg = string.IsNullOrEmpty(message) ? ("服务返回码 " + gatewayCode) : message;
  229. return gatewayCode;
  230. }
  231. outputData = ExtractStringField(responseText, "output") ?? string.Empty;
  232. return 0;
  233. }
  234. catch (Exception ex)
  235. {
  236. pErrMsg = "调用异常:" + ex.Message;
  237. return -1;
  238. }
  239. }
  240. private static string BuildInvokeBody(string func, string[] args, string progId)
  241. {
  242. var builder = new StringBuilder();
  243. builder.Append("{\"func\":").Append(Quote(func));
  244. builder.Append(",\"args\":[");
  245. if (args != null)
  246. {
  247. for (int i = 0; i < args.Length; i++)
  248. {
  249. if (i > 0) builder.Append(',');
  250. builder.Append(Quote(args[i]));
  251. }
  252. }
  253. builder.Append(']');
  254. if (!string.IsNullOrEmpty(progId))
  255. {
  256. builder.Append(",\"progId\":").Append(Quote(progId));
  257. }
  258. builder.Append('}');
  259. return builder.ToString();
  260. }
  261. private static string Quote(string value)
  262. {
  263. if (value == null) return "\"\"";
  264. var builder = new StringBuilder(value.Length + 16);
  265. builder.Append('"');
  266. foreach (char c in value)
  267. {
  268. switch (c)
  269. {
  270. case '"': builder.Append("\\\""); break;
  271. case '\\': builder.Append("\\\\"); break;
  272. case '\b': builder.Append("\\b"); break;
  273. case '\f': builder.Append("\\f"); break;
  274. case '\n': builder.Append("\\n"); break;
  275. case '\r': builder.Append("\\r"); break;
  276. case '\t': builder.Append("\\t"); break;
  277. default:
  278. if (c < 0x20)
  279. {
  280. builder.Append("\\u").Append(((int)c).ToString("x4"));
  281. }
  282. else
  283. {
  284. builder.Append(c);
  285. }
  286. break;
  287. }
  288. }
  289. builder.Append('"');
  290. return builder.ToString();
  291. }
  292. private int Post(string path, string body, out string responseText)
  293. {
  294. responseText = string.Empty;
  295. HttpWebResponse response = null;
  296. try
  297. {
  298. var request = CreateRequest(path, "POST");
  299. byte[] bytes = Encoding.UTF8.GetBytes(body ?? string.Empty);
  300. request.ContentLength = bytes.Length;
  301. using (Stream stream = request.GetRequestStream())
  302. {
  303. stream.Write(bytes, 0, bytes.Length);
  304. }
  305. response = (HttpWebResponse)request.GetResponse();
  306. responseText = ReadResponse(response);
  307. return (int)response.StatusCode == 401 ? -6 : 0;
  308. }
  309. catch (WebException ex)
  310. {
  311. return TranslateWebException(ex, out responseText);
  312. }
  313. finally
  314. {
  315. if (response != null) response.Close();
  316. }
  317. }
  318. private int Get(string path, out string responseText)
  319. {
  320. responseText = string.Empty;
  321. HttpWebResponse response = null;
  322. try
  323. {
  324. var request = CreateRequest(path, "GET");
  325. response = (HttpWebResponse)request.GetResponse();
  326. responseText = ReadResponse(response);
  327. return (int)response.StatusCode == 401 ? -6 : 0;
  328. }
  329. catch (WebException ex)
  330. {
  331. return TranslateWebException(ex, out responseText);
  332. }
  333. finally
  334. {
  335. if (response != null) response.Close();
  336. }
  337. }
  338. private HttpWebRequest CreateRequest(string path, string method)
  339. {
  340. var request = (HttpWebRequest)WebRequest.Create(BaseUrl + path);
  341. request.Method = method;
  342. request.Timeout = TimeoutMs;
  343. request.ReadWriteTimeout = TimeoutMs;
  344. request.ContentType = "application/json; charset=utf-8";
  345. request.Accept = "application/json";
  346. request.Proxy = null; // 本机不走代理,避免首次探测耗时
  347. request.KeepAlive = true;
  348. request.UserAgent = "BeiJingComClient";
  349. if (!string.IsNullOrEmpty(AccessToken))
  350. {
  351. request.Headers["X-Access-Token"] = AccessToken;
  352. }
  353. return request;
  354. }
  355. private string ReadResponse(HttpWebResponse response)
  356. {
  357. using (Stream stream = response.GetResponseStream())
  358. {
  359. if (stream == null) return string.Empty;
  360. Encoding encoding = Encoding.UTF8;
  361. try
  362. {
  363. if (!string.IsNullOrEmpty(response.CharacterSet))
  364. {
  365. encoding = Encoding.GetEncoding(response.CharacterSet);
  366. }
  367. }
  368. catch
  369. {
  370. encoding = Encoding.UTF8;
  371. }
  372. using (var reader = new StreamReader(stream, encoding))
  373. {
  374. return reader.ReadToEnd();
  375. }
  376. }
  377. }
  378. private int TranslateWebException(WebException ex, out string responseText)
  379. {
  380. responseText = string.Empty;
  381. if (ex.Status == WebExceptionStatus.Timeout)
  382. {
  383. responseText = "调用超时(" + TimeoutMs + "ms)。请求可能已提交至 COM,请勿重复提交。";
  384. return -2;
  385. }
  386. var httpResponse = ex.Response as HttpWebResponse;
  387. if (httpResponse != null)
  388. {
  389. try
  390. {
  391. responseText = ReadResponse(httpResponse);
  392. }
  393. catch
  394. {
  395. responseText = string.Empty;
  396. }
  397. int status = (int)httpResponse.StatusCode;
  398. if (status == 401) return -6;
  399. if (string.IsNullOrEmpty(responseText))
  400. {
  401. responseText = "服务返回 HTTP " + status;
  402. }
  403. return status >= 500 ? -1 : -7;
  404. }
  405. if (ex.Status == WebExceptionStatus.ConnectFailure ||
  406. ex.Status == WebExceptionStatus.NameResolutionFailure)
  407. {
  408. responseText = "无法连接本地 COM 服务(" + BaseUrl + ")。请确认 BeiJingComService 已启动、端口未被占用或安全软件拦截。";
  409. return -5;
  410. }
  411. responseText = "HTTP 通讯异常(" + ex.Status + "): " + ex.Message;
  412. return -5;
  413. }
  414. // -------- 极简 JSON 取值:只处理形如 "key":"value" 的一级节点,够用且不引依赖 --------
  415. private static string ExtractStringField(string json, string field)
  416. {
  417. if (string.IsNullOrEmpty(json)) return null;
  418. string key = "\"" + field + "\"";
  419. int keyIndex = json.IndexOf(key, StringComparison.Ordinal);
  420. if (keyIndex < 0) return null;
  421. int colon = json.IndexOf(':', keyIndex + key.Length);
  422. if (colon < 0) return null;
  423. int i = colon + 1;
  424. while (i < json.Length && char.IsWhiteSpace(json[i])) i++;
  425. if (i >= json.Length || json[i] != '"')
  426. {
  427. // 处理 null
  428. if (i + 3 < json.Length && string.CompareOrdinal(json, i, "null", 0, 4) == 0) return null;
  429. return null;
  430. }
  431. i++;
  432. var builder = new StringBuilder();
  433. while (i < json.Length)
  434. {
  435. char c = json[i];
  436. if (c == '"') break;
  437. if (c == '\\' && i + 1 < json.Length)
  438. {
  439. char next = json[i + 1];
  440. switch (next)
  441. {
  442. case '"': builder.Append('"'); break;
  443. case '\\': builder.Append('\\'); break;
  444. case '/': builder.Append('/'); break;
  445. case 'b': builder.Append('\b'); break;
  446. case 'f': builder.Append('\f'); break;
  447. case 'n': builder.Append('\n'); break;
  448. case 'r': builder.Append('\r'); break;
  449. case 't': builder.Append('\t'); break;
  450. case 'u':
  451. if (i + 5 < json.Length)
  452. {
  453. int value;
  454. if (int.TryParse(json.Substring(i + 2, 4), System.Globalization.NumberStyles.HexNumber,
  455. System.Globalization.CultureInfo.InvariantCulture, out value))
  456. {
  457. builder.Append((char)value);
  458. }
  459. i += 4;
  460. }
  461. break;
  462. default: builder.Append(next); break;
  463. }
  464. i += 2;
  465. continue;
  466. }
  467. builder.Append(c);
  468. i++;
  469. }
  470. return builder.ToString();
  471. }
  472. private static int ExtractIntField(string json, string field)
  473. {
  474. if (string.IsNullOrEmpty(json)) return int.MinValue;
  475. string key = "\"" + field + "\"";
  476. int keyIndex = json.IndexOf(key, StringComparison.Ordinal);
  477. if (keyIndex < 0) return int.MinValue;
  478. int colon = json.IndexOf(':', keyIndex + key.Length);
  479. if (colon < 0) return int.MinValue;
  480. int i = colon + 1;
  481. while (i < json.Length && char.IsWhiteSpace(json[i])) i++;
  482. if (i >= json.Length) return int.MinValue;
  483. bool negative = false;
  484. if (json[i] == '-') { negative = true; i++; }
  485. else if (json[i] == '+') { i++; }
  486. long value = 0;
  487. int digits = 0;
  488. while (i < json.Length && json[i] >= '0' && json[i] <= '9')
  489. {
  490. value = value * 10 + (json[i] - '0');
  491. digits++;
  492. i++;
  493. if (digits > 10) break;
  494. }
  495. if (digits == 0) return int.MinValue;
  496. return (int)(negative ? -value : value);
  497. }
  498. private static bool ExtractBoolField(string json, string field)
  499. {
  500. if (string.IsNullOrEmpty(json)) return false;
  501. string key = "\"" + field + "\"";
  502. int keyIndex = json.IndexOf(key, StringComparison.Ordinal);
  503. if (keyIndex < 0) return false;
  504. int colon = json.IndexOf(':', keyIndex + key.Length);
  505. if (colon < 0) return false;
  506. int i = colon + 1;
  507. while (i < json.Length && char.IsWhiteSpace(json[i])) i++;
  508. if (i + 3 < json.Length && string.CompareOrdinal(json, i, "true", 0, 4) == 0) return true;
  509. return false;
  510. }
  511. }
  512. }