using AKSWebBrowser.Commen; using Newtonsoft.Json.Linq; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.WebSockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Net.Sockets; using System.Timers; using CPF.Mac.Foundation; using CPF.Windows; namespace AksWebBrowser.Common { public class WebSocketClientWithHeartbeat { private readonly string _serverUri; private readonly ClientWebSocket _webSocket = new ClientWebSocket(); public string funName = string.Empty; public bool isstop = true; //开启定时 System.Timers.Timer timer = new System.Timers.Timer(30000); public WebSocketClientWithHeartbeat() { try { _serverUri = Parame.smWebsocket; _webSocket.ConnectAsync(new Uri(_serverUri), CancellationToken.None); Parame.webSocket = _webSocket; ReceiveMessages(); SendHeartbeats(); } catch (Exception ex) { Log.Error("连接双目webSocket" + ex.Message); } } /// /// 接收消息 /// /// private async Task ReceiveMessages() { if (Parame.webSocket.State == WebSocketState.Open) { try { var buffer = new byte[1024 * 1024 * 5]; var result = await Parame.webSocket.ReceiveAsync(new ArraySegment(buffer), CancellationToken.None); if (result.MessageType == WebSocketMessageType.Close) { // 关闭处理逻辑 await Parame.webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None); } else { // 处理接收到的消息逻辑 string body = System.Text.Encoding.UTF8.GetString(buffer, 0, result.Count); if (!string.IsNullOrEmpty(body) && Parame.socket!=null) { JObject jo = (JObject)JsonConvert.DeserializeObject(body); string functionName = jo["functionName"].ToString(); if (functionName == "CF_OpenCamera") { string status = jo["success"].ToString(); if (status == "0") { //开始活检 Send("{\"function\":\"CF_StartLiveDetect\"}", "CF_StartLiveDetect"); } else { Log.Error("启用异常补偿服务1!"); timer.Stop(); isstop = false; string commod = "cd /opt/lhtserver/files/bin && nohup ./LhtCamServer.sh &"; MainModel.Bash(commod); Task.Delay(200).Wait(); MainModel.StartFace(); Log.Error("启用成功1!"); } } else if (functionName == "LiveDetectResult") { string status = string.Empty; if (body.Contains("success")) { status = jo["success"].ToString(); } if (string.IsNullOrEmpty(status)) { string nEventId = jo["nEventId"].ToString(); if (nEventId == "100") { string results = Parame.ImgBase64; if (!string.IsNullOrEmpty(results)) { string ImageBase64 = Parame.ImgBase64; string faceA = Utils.Base64ByImagesPath(ImageBase64.Replace("data:image/jpg;base64,", ""), "faceA"); string faceB = Utils.Base64ByImagesPath(jo["ImgBase64"].ToString(), "faceB"); var mode2 = new { function = "CF_FaceCompare", filePathA = faceA, filePathB = faceB }; timer.Stop(); //开始人脸比对 Send(JsonConvert.SerializeObject(mode2), "CF_FaceCompare"); } else { timer.Stop(); results = "{\"timestamp\":\"" + Utils.GetTimestamp() + "\",\"keycode\":\"" + "aks100120" + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "人证合一验证失败." + "\"}"; Parame.socket.Send(results); isstop = false; } } } } else if (functionName == "CF_FaceCompare") { //停止活检 Send("{\"function\":\"CF_StopLiveDetect\"}", "CF_StopLiveDetect"); //关闭摄像头 Send("{\"function\":\"CF_CloseCamera\"}", "CF_CloseCamera"); string status = jo["success"].ToString(); string results = string.Empty; if (status == "0") { results = "{\"timestamp\":\"" + Utils.GetTimestamp() + "\",\"keycode\":\"" + "aks100120" + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":\"" + "人证合一验证成功." + "\"}"; } else { results = "{\"timestamp\":\"" + Utils.GetTimestamp() + "\",\"keycode\":\"" + "aks100120" + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "人证合一验证失败." + "\"}"; } timer.Stop(); Parame.socket.Send(results); isstop = false; } else if (functionName == "VideoStream") { string VideoBase64 = jo["VideoBase64"].ToString(); string src = "data:image/jpg;base64," + VideoBase64; string results = "{\"timestamp\":\"" + Utils.GetTimestamp() + "\",\"keycode\":\"" + "aks100121" + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":\"" + src + "\"}"; Parame.socket.Send(results); } } } } catch (Exception ex) { Log.Error("接收消息双目websockt" + ex.Message); } } } /// /// 发送心跳 /// /// private async Task SendHeartbeats() { while (true) { if (Parame.webSocket.State == WebSocketState.Open) { try { // 心跳消息逻辑 var heartbeat = "{\"function\":\"Heartbeat\"}"; var sendBuffer = System.Text.Encoding.UTF8.GetBytes(heartbeat); await Parame.webSocket.SendAsync(new ArraySegment(sendBuffer), WebSocketMessageType.Text, true, CancellationToken.None); await Task.Delay(10000); //根据需要设置心跳间隔 } catch (Exception ex) { Log.Error("心跳消息逻辑双目websockt" + ex.Message); } } } } /// /// 推送消息到双目websockt /// /// /// public async Task Send(string message, string _funName) { try { funName = _funName; Parame.messageData = string.Empty; if (Parame.webSocket.State == WebSocketState.Open) { // 发送消息到服务器 var buffer = System.Text.Encoding.UTF8.GetBytes(message); await Parame.webSocket.SendAsync(new ArraySegment(buffer), WebSocketMessageType.Text, true, CancellationToken.None); } if (_funName == "CF_StartLiveDetect") { timer.Elapsed += OnTimedEvent; timer.Enabled = true;//启动定时器 } } catch (Exception ex) { Log.Error("推送消息到双目websockt" + ex.Message); } } //打开串口 private void OnTimedEvent(Object source, ElapsedEventArgs e) { try { timer.Stop(); //停止活检 Send("{\"function\":\"CF_StopLiveDetect\"}", "CF_StopLiveDetect"); //关闭摄像头 Send("{\"function\":\"CF_CloseCamera\"}", "CF_CloseCamera"); string results = "{\"timestamp\":\"" + Utils.GetTimestamp() + "\",\"keycode\":\"" + "aks100120" + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "活体检测超时." + "\"}"; Parame.socket.Send(results); isstop = false; } catch { } finally { } } /// /// 关闭双目websockt /// /// public async Task Close() { try { if (Parame.webSocket.State == WebSocketState.Open) { isstop = false; await Parame.webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None); } } catch (Exception ex) { Log.Error("关闭双目websockt" + ex.Message); } } } }