采用网络对联方式交互数据
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

433 lines
24 KiB

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Linq;
using System.Collections.Concurrent;
using System.Configuration;
using System.Threading.Tasks;
using DevicesService.Common;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Drawing;
using System.IO.Ports;
using System.IO;
using System.Reflection;
using System.Buffers.Text;
using System.Globalization;
namespace DevicesService.Commen
{
/// <summary>
/// tcp Socket监听基库
/// </summary>
public class TcpServer
{
public static List<TcpClient> clients = new List<TcpClient>();
private static ScriptCallbackObject scriptCallback = new ScriptCallbackObject();
public void Start()
{
try
{
TcpListener listener = new TcpListener(IPAddress.Any, 1234);
listener.Start();
Console.WriteLine("服务器已启动,等待客户端连接...");
Timer timer = new Timer(SendHelloMessage, null, TimeSpan.Zero, TimeSpan.FromSeconds(20));
while (true)
{
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("客户端已连接:{0}", client.Client.RemoteEndPoint);
clients.Add(client);
// 启动线程,接收客户端消息
ThreadPool.QueueUserWorkItem(ReceiveMessage, client);
}
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
finally { }
}
/// <summary>
/// 发送数据
/// </summary>
/// <param name="client"></param>
/// <param name="message"></param>
public static void SendDataWithHeader(TcpClient client, string message)
{
try
{
if (client != null)
{
byte[] messageBytes = Encoding.UTF8.GetBytes(message);
byte[] header = BitConverter.GetBytes(messageBytes.Length);
byte[] data = new byte[header.Length + messageBytes.Length];
Array.Copy(header, 0, data, 0, header.Length);
Array.Copy(messageBytes, 0, data, header.Length, messageBytes.Length);
NetworkStream stream = client.GetStream();
stream.Write(data, 0, data.Length);
}
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
finally { }
}
/// <summary>
/// 发送一个Hello的方法
/// </summary>
/// <param name="state"></param>
public static void SendHelloMessage(object state)
{
try
{
foreach (TcpClient client in clients)
{
try
{
SendDataWithHeader(client, " heartbeatService");
}
catch (Exception ex)
{
Console.WriteLine("向客户端 {0} 发送消息失败:{1}", client.Client.RemoteEndPoint, ex.Message);
clients.Remove(client);
break;
}
}
}
catch { }
finally { }
}
/// <summary>
/// 读取客户端信息
/// </summary>
/// <param name="state"></param>
public static void ReceiveMessage(object state)
{
TcpClient client = (TcpClient)state;
if (client != null)
{
NetworkStream stream = client.GetStream();
while (true)
{
try
{
// 读取包头,获取消息的大小
int messageSize = ReadHeader(stream);
// 读取消息内容
byte[] buffer = new byte[messageSize];
int bytesRead = ReadExactly(stream, buffer, 0, messageSize);
if (bytesRead < messageSize)
{
Console.WriteLine("无法读取消息,可能是连接断开:{0}", client.Client.RemoteEndPoint);
clients.Remove(client);
break;
}
string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
if (!message.Contains("heartbeatClient") || message != "keepAlive")
{
Console.WriteLine("收到客户端消息:{0}", message);
string indata = message;
if (!string.IsNullOrEmpty(indata))
{
string result = Util.Base64str2(indata);
//Log.Info("接收到COM口传来数据:" + result);
if (!string.IsNullOrEmpty(result))
{
JObject jo = (JObject)JsonConvert.DeserializeObject(result);
int type = Convert.ToInt32(jo["type"].ToString());
string param = jo["param"].ToString();
string resultback = string.Empty;
string base64 = string.Empty;
string data = string.Empty;
string callback = jo["callback"].ToString();
JObject joparam;
switch (type)
{
//{"type":"1","param":{"data":""}}
case Func.IDCardRead:
#region 读取身份证
try
{
joparam = (JObject)JsonConvert.DeserializeObject(param);
data = joparam["data"].ToString();
resultback = scriptCallback.IDCardRead(data, callback);
//Console.WriteLine(resultback);
Log.Info("读取身份证 返回数据:" + resultback);
base64 = Util.str2Base64(resultback);
//向com对方发送数据
SendDataWithHeader(client, base64);
}
catch (Exception ex)
{
string rest = "{\"callback\":\"" + "callback" + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}";
base64 = Util.str2Base64(rest);
SendDataWithHeader(client, base64);
}
#endregion
break;
//{"type":"2","param":{"ph":"A012","ddrs":"10","qrcode":"www.baidu.com/s?wd=国家赔偿","ywmc":"国家赔偿"}}
case Func.SendByPrint:
#region 打印排队票据
try
{
joparam = (JObject)JsonConvert.DeserializeObject(param);
string ph = joparam["ph"].ToString();
string ddrs = joparam["ddrs"].ToString();
string qrcode = joparam["qrcode"].ToString();
string ywmc = joparam["ywmc"].ToString();
resultback = scriptCallback.SendByPrint(ph, ddrs, qrcode, ywmc, callback);
//Log.Info("打印排队票据 返回数据:" + resultback);
base64 = Util.str2Base64(resultback);
//向com对方发送数据
SendDataWithHeader(client, base64);
}
catch (Exception ex)
{
string rest = "{\"callback\":\"" + "callback" + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}";
base64 = Util.str2Base64(rest);
SendDataWithHeader(client, base64);
}
#endregion
break;
//{"type":"3","param":{"text":"欢迎使用阿凯思控诉业务一体机","ispaye":false}}
case Func.payleText:
#region 文字语音播报
try
{
joparam = (JObject)JsonConvert.DeserializeObject(param);
data = joparam["text"].ToString();
bool ispaye = Convert.ToBoolean(joparam["ispaye"].ToString());
resultback = scriptCallback.payleText(data, ispaye, callback);
//Console.WriteLine(resultback);
Log.Info("文字语音播报 返回数据:" + resultback);
base64 = Util.str2Base64(resultback);
//向com对方发送数据
SendDataWithHeader(client, base64);
}
catch (Exception ex)
{
string rest = "{\"callback\":\"" + "callback" + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}";
base64 = Util.str2Base64(rest);
SendDataWithHeader(client, base64);
}
#endregion
break;
//{"type":"4","param":{"content":"欢迎使用阿凯思控诉业务一体机","phone":"13333333333"}}
case Func.SendSSM:
#region 发送短信
try
{
joparam = (JObject)JsonConvert.DeserializeObject(param);
string content = joparam["content"].ToString();
string phone = joparam["phone"].ToString();
resultback = scriptCallback.SendSSM(content, phone, callback);
//Log.Info("发送短信 返回数据:" + resultback);
base64 = Util.str2Base64(resultback);
//向com对方发送数据
SendDataWithHeader(client, base64);
}
catch (Exception ex)
{
string rest = "{\"callback\":\"" + "callback" + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}";
base64 = Util.str2Base64(rest);
SendDataWithHeader(client, base64);
}
#endregion
break;
//{"type":"5","param":{"url":"http://192.168.0.34:92/api/UploadFP/UploadFP"}}
case Func.openCamera:
#region 打开高拍仪并且进行快速扫描文件
try
{
joparam = (JObject)JsonConvert.DeserializeObject(param);
data = joparam["url"].ToString();
resultback = scriptCallback.openCamera(data, callback);
//Log.Info("打开高拍仪并且进行快速扫描文件 返回数据:" + resultback);
//base64 = Util.str2Base64(resultback);
//向com对方发送数据
SendDataWithHeader(client, resultback);
}
catch (Exception ex)
{
string rest = "{\"callback\":\"" + "callback" + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}";
base64 = Util.str2Base64(rest);
SendDataWithHeader(client, base64);
}
#endregion
break;
//{"type":"6","param":{"data":""}}
case Func.OpenSign:
#region 打开签字版数据
try
{
joparam = (JObject)JsonConvert.DeserializeObject(param);
data = joparam["data"].ToString();
resultback = scriptCallback.OpenSign(data, callback);
//Log.Info("打开签字版数据 返回数据:" + resultback);
base64 = Util.str2Base64(resultback);
//向com对方发送数据
SendDataWithHeader(client, base64);
}
catch (Exception ex)
{
string rest = "{\"callback\":\"" + "callback" + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}";
base64 = Util.str2Base64(rest);
SendDataWithHeader(client, base64);
}
#endregion
break;
//{"type":"7","param":{"data":""}}
case Func.CloseSign:
#region 关闭签字版数据
try
{
joparam = (JObject)JsonConvert.DeserializeObject(param);
data = joparam["data"].ToString();
resultback = scriptCallback.CloseSign(data, callback);
//Log.Info("关闭签字版数据 返回数据:" + resultback);
base64 = Util.str2Base64(resultback);
//向com对方发送数据
SendDataWithHeader(client, base64);
}
catch (Exception ex)
{
string rest = "{\"callback\":\"" + "callback" + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}";
base64 = Util.str2Base64(rest);
SendDataWithHeader(client, base64);
}
#endregion
break;
//{"type":"8","param":{"url":"http://192.168.0.34:92/api/UploadFP/UploadFP"}}
case Func.GetSignData:
#region 获取签字版数据
try
{
resultback = scriptCallback.GetSignData(data, callback);
//Log.Info("获取签字版数据 返回数据:" + resultback);
//base64 = Util.str2Base64(resultback);
//向com对方发送数据
SendDataWithHeader(client, resultback);
}
catch (Exception ex)
{
string rest = "{\"callback\":\"" + "callback" + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}";
base64 = Util.str2Base64(rest);
SendDataWithHeader(client, base64);
}
#endregion
break;
//开始录音:{"type":"11","param":{"url":"","isopen":true}}
//结束录音:{"type":"11","param":{"url":"http://192.168.0.34:92/api/UploadFP/UploadFP","isopen":false}}
//取消录音:{"type":"11","param":{"url":"","isopen":false}}
case Func.SoundRecording:
#region 开始录音、取消录音、结束录音
try
{
joparam = (JObject)JsonConvert.DeserializeObject(param);
string url = joparam["url"].ToString();
bool isopen = Convert.ToBoolean(joparam["isopen"].ToString());
resultback = scriptCallback.SoundRecording(isopen, url, callback);
Log.Info("开始录音、取消录音、结束录音 返回数据:" + resultback);
base64 = Util.str2Base64(resultback);
//向com对方发送数据
SendDataWithHeader(client, base64);
}
catch (Exception ex)
{
string rest = "{\"callback\":\"" + "callback" + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}";
base64 = Util.str2Base64(rest);
SendDataWithHeader(client, base64);
}
#endregion
break;
default:
string str = "{\"callback\":\"" + "callback" + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "调用方法不存在" + "\"}";
base64 = Util.str2Base64(str);
SendDataWithHeader(client, base64);
break;
}
}
else
{
string str = "{\"callback\":\"" + "callback" + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "参数不能为空" + "\"}";
string base64 = Util.str2Base64(str);
SendDataWithHeader(client, base64);
}
}
}
if (message == "keepAlive")
{
// 客户端发送心跳指令,关闭连接
Console.WriteLine("客户端发送了心跳指令,关闭连接:{0}", client.Client.RemoteEndPoint);
clients.Remove(client);
client.Close();
break;
}
}
catch { }
finally { }
GC.Collect();
}
}
}
/// <summary>
/// 解析包头里面有多少字节
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
public static int ReadHeader(NetworkStream stream)
{
try
{
byte[] header = new byte[4];
int headerBytesRead = stream.Read(header, 0, 4);
if (headerBytesRead < 4)
{
return -1;
}
return BitConverter.ToInt32(header, 0);
}
catch { return -1; }
finally { }
}
/// <summary>
/// 等待流全部获取到,然后丢出去
/// </summary>
/// <param name="stream"></param>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="count"></param>
/// <returns></returns>
public static int ReadExactly(NetworkStream stream, byte[] buffer, int offset, int count)
{
try
{
int bytesRead = 0;
while (bytesRead < count)
{
int result = stream.Read(buffer, offset + bytesRead, count - bytesRead);
if (result == 0)
{
// 连接断开或遇到流的末尾
return bytesRead;
}
bytesRead += result;
}
return bytesRead;
}
catch { return -1; }
finally { }
}
}
}