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);
Task.Delay(200).Wait();
ReceiveMessages();
SendHeartbeats();
}
catch (Exception ex)
{
Log.Error("连接双目webSocket" + ex.Message);
}
}
///
/// 接收消息
///
///
private async Task ReceiveMessages()
{
while (isstop)
{
if (_webSocket.State == WebSocketState.Open)
{
try
{
var buffer = new byte[1024 * 1024 * 5];
var result = await _webSocket.ReceiveAsync(new ArraySegment(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close)
{
// 关闭处理逻辑
await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
}
else
{
// 处理接收到的消息逻辑
string body = System.Text.Encoding.UTF8.GetString(buffer, 0, result.Count);
if (!string.IsNullOrEmpty(body))
{
JObject jo = (JObject)JsonConvert.DeserializeObject(body);
string functionName = jo["functionName"].ToString();
if (functionName == "LiveDetectResult")
{
Log.Error("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);
// 断开连接
_webSocket.Dispose();
}
}
}
}
else if (functionName == "CF_FaceCompare")
{
Log.Error("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);
// 断开连接
_webSocket.Dispose();
isstop = false;
}
else if (functionName == "VideoStream")
{
Log.Error("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 (isstop)
{
if (_webSocket.State == WebSocketState.Open)
{
try
{
// 心跳消息逻辑
var heartbeat = "{\"function\":\"Heartbeat\"}";
var sendBuffer = System.Text.Encoding.UTF8.GetBytes(heartbeat);
await _webSocket.SendAsync(new ArraySegment(sendBuffer), WebSocketMessageType.Text, true, CancellationToken.None);
await Task.Delay(TimeSpan.FromSeconds(10), CancellationToken.None); //根据需要设置心跳间隔
}
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 (_webSocket.State == WebSocketState.Open)
{
// 发送消息到服务器
var buffer = System.Text.Encoding.UTF8.GetBytes(message);
await _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);
// 断开连接
_webSocket.Dispose();
isstop = false;
}
catch { }
finally { }
}
///
/// 关闭双目websockt
///
///
public async Task Close()
{
try
{
if (_webSocket.State == WebSocketState.Open)
{
isstop = false;
await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
}
}
catch (Exception ex)
{
Log.Error("关闭双目websockt" + ex.Message);
}
}
}
}