| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574 |
- using System;
- using System.IO;
- using System.Net;
- using System.Text;
- namespace BeiJingComService.Client
- {
- /// <summary>
- /// HIS 侧本地 COM 通讯客户端。整个文件可原样拷贝到 HIS 工程使用,
- /// 只依赖 System / System.Net,不需要任何第三方库(无 Newtonsoft)。
- ///
- /// 替换关系:
- /// 旧:Business(inputData, ref outputData, ref pErrMsg) → 直接 P/Invoke DLL
- /// 新:Invoke(func, args, out outputData, out pErrMsg) → HTTP 调用本机 COM 服务
- ///
- /// 之所以把 COM 调用搬到独立进程,是为了:
- /// 1) COM 实例在服务进程内常驻复用(只在首次/空闲超时后 open),读卡不再慢;
- /// 2) HIS 进程只需发 HTTP,不加载也不依赖任何医保 COM/OCX 组件。
- ///
- /// 编码:HIS ←→ 服务为 UTF-8;COM 侧编码由服务进程内部处理,HIS 无需关心。
- /// </summary>
- public class ComClient
- {
- static ComClient()
- {
- // 关闭 100-Continue:否则每次 POST 都要多一个往返,读卡会明显变慢
- ServicePointManager.Expect100Continue = false;
- // 关闭 Nagle:报文一次发完,不要攒包
- ServicePointManager.UseNagleAlgorithm = false;
- // 多窗口并发时不被默认 2 连接限制卡住
- ServicePointManager.DefaultConnectionLimit = 64;
- ServicePointManager.CheckCertificateRevocationList = false;
- }
- /// <summary>服务地址,末尾不要带斜杠。</summary>
- public string BaseUrl { get; private set; }
- /// <summary>访问令牌,与服务 App.config 的 AccessToken 一致;服务留空则这里也留空。</summary>
- public string AccessToken { get; private set; }
- /// <summary>超时时间(毫秒)。必须大于服务的 ComTimeoutMs(默认 60000),建议 90000。</summary>
- public int TimeoutMs { get; private set; }
- public ComClient(string baseUrl = "http://127.0.0.1:5001", string accessToken = null, int timeoutMs = 90000)
- {
- BaseUrl = (baseUrl ?? "http://127.0.0.1:5001").TrimEnd('/');
- AccessToken = accessToken ?? string.Empty;
- TimeoutMs = timeoutMs > 0 ? timeoutMs : 90000;
- }
- // =====================================================================
- // 通用调用
- // =====================================================================
- /// <summary>
- /// 调用一个本地 COM 方法。
- /// </summary>
- /// <param name="func">COM 方法名,如 open / close / ReadCardObj / BussniessObj / Trade / TradeAll。</param>
- /// <param name="args">按顺序对应 COM 方法的各参数;为 null 或空表示无参(open/close 形态)。</param>
- /// <param name="outputData">成功时为 COM 方法最后一个参数的最终值;失败时为空串。</param>
- /// <param name="pErrMsg">错误信息;成功时为空串。</param>
- /// <returns>
- /// 0 调用成功
- /// -1 执行异常(COM 方法内部抛错)
- /// -2 调用超时(请求已提交至 COM,结果作废,严禁重复提交)
- /// -3 服务未初始化 / 已停止
- /// -4 请求报文为空或参数错误
- /// -5 无法连接服务(服务没启动 / 端口被改 / 被安全软件拦截)
- /// -6 令牌校验失败(HTTP 401)
- /// -7 服务返回了无法识别的结果
- /// </returns>
- public int Invoke(string func, string[] args, out string outputData, out string pErrMsg)
- {
- return Invoke(func, args, null, out outputData, out pErrMsg);
- }
- /// <summary>
- /// 调用指定 ProgID 的 COM 方法。progId 为空时使用服务的主组件(MedicareCom.Outpatient)。
- /// </summary>
- public int Invoke(string func, string[] args, string progId, out string outputData, out string pErrMsg)
- {
- outputData = string.Empty;
- pErrMsg = string.Empty;
- if (string.IsNullOrWhiteSpace(func))
- {
- pErrMsg = "入参 func 为空";
- return -4;
- }
- try
- {
- string body = BuildInvokeBody(func, args, progId);
- string responseText;
- int code = Post("/api/com/invoke", body, out responseText);
- if (code != 0)
- {
- pErrMsg = responseText;
- return code;
- }
- // 解服务包装:{"code":0,"message":"","elapsedMs":123,"output":"..."}
- int gatewayCode = ExtractIntField(responseText, "code");
- string message = ExtractStringField(responseText, "message");
- if (gatewayCode != 0)
- {
- pErrMsg = string.IsNullOrEmpty(message) ? ("服务返回码 " + gatewayCode) : message;
- return gatewayCode;
- }
- outputData = ExtractStringField(responseText, "output") ?? string.Empty;
- return 0;
- }
- catch (Exception ex)
- {
- pErrMsg = "调用(Invoke)异常:" + ex.Message;
- return -1;
- }
- }
- /// <summary>建立 COM 会话(等价于调用 COM 的 open)。一般无需手工调用,服务会按需自动 open。</summary>
- public int Open(out string outputData, out string pErrMsg)
- {
- return PostConvenience("/api/com/open", out outputData, out pErrMsg);
- }
- /// <summary>关闭 COM 会话(等价于调用 COM 的 close)。</summary>
- public int Close(out string outputData, out string pErrMsg)
- {
- return PostConvenience("/api/com/close", out outputData, out pErrMsg);
- }
- /// <summary>
- /// 读卡:服务端封装了 open → GetPersonClass_Multimedia → GetPersonInfo(Nation)_Multimedia。
- /// </summary>
- /// <param name="input">HIS 侧拼接的内层 XML(形如 <multiclass>...</multiclass>...<officeName>...</officeName>),
- /// 服务端负责按 GetinPar 包装成完整报文体。</param>
- /// <param name="cardClass">中心返回的人员类别:1 本市、2 异地;取不到时为空串。</param>
- /// <param name="outputData">成功时为最终参保信息返回 XML。</param>
- /// <param name="pErrMsg">错误信息;成功时为空串。</param>
- /// <returns>同 Invoke 的结果码约定(0 成功,-2 超时,-3 未就绪,-4 参数错误,-5 连不上,-6 令牌失败)。</returns>
- public int ReadCard(string input, out string cardClass, out string outputData, out string pErrMsg)
- {
- cardClass = string.Empty;
- outputData = string.Empty;
- pErrMsg = string.Empty;
- if (string.IsNullOrWhiteSpace(input))
- {
- pErrMsg = "读卡入参 input 为空";
- return -4;
- }
- try
- {
- string body = "{\"input\":" + Quote(input) + "}";
- string responseText;
- int code = Post("/api/card/read", body, out responseText);
- if (code != 0)
- {
- pErrMsg = responseText;
- return code;
- }
- int gatewayCode = ExtractIntField(responseText, "code");
- string message = ExtractStringField(responseText, "message");
- cardClass = ExtractStringField(responseText, "cardClass") ?? string.Empty;
- if (gatewayCode != 0)
- {
- pErrMsg = string.IsNullOrEmpty(message) ? ("服务返回码 " + gatewayCode) : message;
- return gatewayCode;
- }
- outputData = ExtractStringField(responseText, "output") ?? string.Empty;
- return 0;
- }
- catch (Exception ex)
- {
- pErrMsg = "读卡(ReadCard)异常:" + ex.Message;
- return -1;
- }
- }
- /// <summary>
- /// 探活。返回 false 时 status 里是原因,可直接提示给操作员。
- /// 建议 HIS 在登录/打开收费窗口时调一次,比等到读卡时才报错友好。
- /// </summary>
- public bool Ping(out string status)
- {
- try
- {
- string responseText;
- int code = Get("/health", out responseText);
- if (code != 0)
- {
- status = responseText;
- return false;
- }
- int gatewayCode = ExtractIntField(responseText, "code");
- if (gatewayCode == -6) { status = "令牌校验失败"; return false; }
- bool initialized = ExtractBoolField(responseText, "initialized");
- bool listening = ExtractBoolField(responseText, "listen");
- status = initialized && listening ? "正常" : "服务未就绪: " + responseText;
- return initialized && listening;
- }
- catch (Exception ex)
- {
- status = ex.Message;
- return false;
- }
- }
- /// <summary>重建网关(COM 实例、工作线程全部重建;进入故障态时使用)。</summary>
- public bool Reinitialize(out string message)
- {
- try
- {
- string responseText;
- int code = Post("/admin/reinitialize", string.Empty, out responseText);
- message = code == 0 ? "服务已重建" : responseText;
- return code == 0;
- }
- catch (Exception ex)
- {
- message = ex.Message;
- return false;
- }
- }
- // =====================================================================
- // 内部实现
- // =====================================================================
- private int PostConvenience(string path, out string outputData, out string pErrMsg)
- {
- outputData = string.Empty;
- pErrMsg = string.Empty;
- try
- {
- string responseText;
- int code = Post(path, string.Empty, out responseText);
- if (code != 0)
- {
- pErrMsg = responseText;
- return code;
- }
- int gatewayCode = ExtractIntField(responseText, "code");
- string message = ExtractStringField(responseText, "message");
- if (gatewayCode != 0)
- {
- pErrMsg = string.IsNullOrEmpty(message) ? ("服务返回码 " + gatewayCode) : message;
- return gatewayCode;
- }
- outputData = ExtractStringField(responseText, "output") ?? string.Empty;
- return 0;
- }
- catch (Exception ex)
- {
- pErrMsg = "调用异常:" + ex.Message;
- return -1;
- }
- }
- private static string BuildInvokeBody(string func, string[] args, string progId)
- {
- var builder = new StringBuilder();
- builder.Append("{\"func\":").Append(Quote(func));
- builder.Append(",\"args\":[");
- if (args != null)
- {
- for (int i = 0; i < args.Length; i++)
- {
- if (i > 0) builder.Append(',');
- builder.Append(Quote(args[i]));
- }
- }
- builder.Append(']');
- if (!string.IsNullOrEmpty(progId))
- {
- builder.Append(",\"progId\":").Append(Quote(progId));
- }
- builder.Append('}');
- return builder.ToString();
- }
- private static string Quote(string value)
- {
- if (value == null) return "\"\"";
- 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"));
- }
- else
- {
- builder.Append(c);
- }
- break;
- }
- }
- builder.Append('"');
- return builder.ToString();
- }
- private int Post(string path, string body, out string responseText)
- {
- responseText = string.Empty;
- HttpWebResponse response = null;
- try
- {
- var request = CreateRequest(path, "POST");
- byte[] bytes = Encoding.UTF8.GetBytes(body ?? string.Empty);
- request.ContentLength = bytes.Length;
- using (Stream stream = request.GetRequestStream())
- {
- stream.Write(bytes, 0, bytes.Length);
- }
- response = (HttpWebResponse)request.GetResponse();
- responseText = ReadResponse(response);
- return (int)response.StatusCode == 401 ? -6 : 0;
- }
- catch (WebException ex)
- {
- return TranslateWebException(ex, out responseText);
- }
- finally
- {
- if (response != null) response.Close();
- }
- }
- private int Get(string path, out string responseText)
- {
- responseText = string.Empty;
- HttpWebResponse response = null;
- try
- {
- var request = CreateRequest(path, "GET");
- response = (HttpWebResponse)request.GetResponse();
- responseText = ReadResponse(response);
- return (int)response.StatusCode == 401 ? -6 : 0;
- }
- catch (WebException ex)
- {
- return TranslateWebException(ex, out responseText);
- }
- finally
- {
- if (response != null) response.Close();
- }
- }
- private HttpWebRequest CreateRequest(string path, string method)
- {
- var request = (HttpWebRequest)WebRequest.Create(BaseUrl + path);
- request.Method = method;
- request.Timeout = TimeoutMs;
- request.ReadWriteTimeout = TimeoutMs;
- request.ContentType = "application/json; charset=utf-8";
- request.Accept = "application/json";
- request.Proxy = null; // 本机不走代理,避免首次探测耗时
- request.KeepAlive = true;
- request.UserAgent = "BeiJingComClient";
- if (!string.IsNullOrEmpty(AccessToken))
- {
- request.Headers["X-Access-Token"] = AccessToken;
- }
- return request;
- }
- private string ReadResponse(HttpWebResponse response)
- {
- using (Stream stream = response.GetResponseStream())
- {
- if (stream == null) return string.Empty;
- Encoding encoding = Encoding.UTF8;
- try
- {
- if (!string.IsNullOrEmpty(response.CharacterSet))
- {
- encoding = Encoding.GetEncoding(response.CharacterSet);
- }
- }
- catch
- {
- encoding = Encoding.UTF8;
- }
- using (var reader = new StreamReader(stream, encoding))
- {
- return reader.ReadToEnd();
- }
- }
- }
- private int TranslateWebException(WebException ex, out string responseText)
- {
- responseText = string.Empty;
- if (ex.Status == WebExceptionStatus.Timeout)
- {
- responseText = "调用超时(" + TimeoutMs + "ms)。请求可能已提交至 COM,请勿重复提交。";
- return -2;
- }
- var httpResponse = ex.Response as HttpWebResponse;
- if (httpResponse != null)
- {
- try
- {
- responseText = ReadResponse(httpResponse);
- }
- catch
- {
- responseText = string.Empty;
- }
- int status = (int)httpResponse.StatusCode;
- if (status == 401) return -6;
- if (string.IsNullOrEmpty(responseText))
- {
- responseText = "服务返回 HTTP " + status;
- }
- return status >= 500 ? -1 : -7;
- }
- if (ex.Status == WebExceptionStatus.ConnectFailure ||
- ex.Status == WebExceptionStatus.NameResolutionFailure)
- {
- responseText = "无法连接本地 COM 服务(" + BaseUrl + ")。请确认 BeiJingComService 已启动、端口未被占用或安全软件拦截。";
- return -5;
- }
- responseText = "HTTP 通讯异常(" + ex.Status + "): " + ex.Message;
- return -5;
- }
- // -------- 极简 JSON 取值:只处理形如 "key":"value" 的一级节点,够用且不引依赖 --------
- 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] != '"')
- {
- // 处理 null
- if (i + 3 < json.Length && string.CompareOrdinal(json, i, "null", 0, 4) == 0) return null;
- 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;
- case 'u':
- if (i + 5 < json.Length)
- {
- int value;
- if (int.TryParse(json.Substring(i + 2, 4), System.Globalization.NumberStyles.HexNumber,
- System.Globalization.CultureInfo.InvariantCulture, out value))
- {
- builder.Append((char)value);
- }
- i += 4;
- }
- break;
- default: builder.Append(next); break;
- }
- i += 2;
- continue;
- }
- builder.Append(c);
- i++;
- }
- return builder.ToString();
- }
- private static int ExtractIntField(string json, string field)
- {
- if (string.IsNullOrEmpty(json)) return int.MinValue;
- string key = "\"" + field + "\"";
- int keyIndex = json.IndexOf(key, StringComparison.Ordinal);
- if (keyIndex < 0) return int.MinValue;
- int colon = json.IndexOf(':', keyIndex + key.Length);
- if (colon < 0) return int.MinValue;
- int i = colon + 1;
- while (i < json.Length && char.IsWhiteSpace(json[i])) i++;
- if (i >= json.Length) return int.MinValue;
- bool negative = false;
- if (json[i] == '-') { negative = true; i++; }
- else if (json[i] == '+') { i++; }
- long value = 0;
- int digits = 0;
- while (i < json.Length && json[i] >= '0' && json[i] <= '9')
- {
- value = value * 10 + (json[i] - '0');
- digits++;
- i++;
- if (digits > 10) break;
- }
- if (digits == 0) return int.MinValue;
- return (int)(negative ? -value : value);
- }
- private static bool ExtractBoolField(string json, string field)
- {
- if (string.IsNullOrEmpty(json)) return false;
- string key = "\"" + field + "\"";
- int keyIndex = json.IndexOf(key, StringComparison.Ordinal);
- if (keyIndex < 0) return false;
- int colon = json.IndexOf(':', keyIndex + key.Length);
- if (colon < 0) return false;
- int i = colon + 1;
- while (i < json.Length && char.IsWhiteSpace(json[i])) i++;
- if (i + 3 < json.Length && string.CompareOrdinal(json, i, "true", 0, 4) == 0) return true;
- return false;
- }
- }
- }
|