using Cksoft.Data; using Cksoft.Data.Repository; using DllEapDal; using DllEapEntity; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace DllEapBll { public class AppletStatusCollectionBll { ILogger logger; public IConfiguration Configuration { get; set; } List CurrMachine = new List(); List CurrTelnet = new List(); IDatabase db = null; public AppletStatusCollectionBll(ILogger logger, IConfiguration configuration) { Configuration = configuration; this.logger = logger; } public static void AppletCollection(ref string errorinfo) { //AppletStatusCollectionBll bll = new AppletStatusCollectionBll(logger); //bll.DoCollection(ref errorinfo); } public void DoCollection(ref string errorinfo) { try { //LogHelper.LogInfo("开始处理机台小程序运行状态---------", "EapAsync", string.Empty); int timeout = Convert.ToInt32(Configuration["timeout"]); var interval = Convert.ToInt32(Configuration["CheckStatusInterval"]); Task.Run(() => { try { while (true) { StringBuilder stringBuilder = new StringBuilder(); logger.LogError("开始处理机台小程序运行状态---------"); IEnumerable models = null; using (IDatabase db = DbFactory.Base("eap")) { var dal = new MachineDal(db); string info = ""; //IEnumerable models = dal.Get(1, 10000, "ID", "", " and a.id in(2,14,268)", info); models = dal.Get(1, 10000, "ID", "", "", ref info); } List ttlist = null; int result = 0; #region //foreach (var item in models) //{ // var telnet = new Telnet("192.168.124.93", 1234, timeout, logger, item); // string err = string.Empty; // telnet.ConnectTcp(ref err); //} #endregion #region List idsOne = new List(); List idsTwo = new List(); var tt = Parallel.ForEach(models, new ParallelOptions { MaxDegreeOfParallelism = 1000 }, item => { if (CheckIPFormat(item.IPAddress)) { string error = ""; Telnet p = new Telnet(item.IPAddress, 5888, timeout, logger, item); if (p.ConnectTcp(ref error)) { if (item.AppletS != 1) { idsOne.Add(item.ID); } logger.LogError(item.FCode + "已开启小程序"); } else { if (item.AppletS != -1) { idsTwo.Add(item.ID); } logger.LogError(item.FCode + "未开启小程序"); } } Thread.Sleep(10); }); if (tt.IsCompleted) { if (idsOne.Count >= 1) { stringBuilder.AppendLine($" update machine set AppletS=1 where id in ({string.Join(",", idsOne.ConvertAll(new Converter(m => m.ToString())).ToArray())}); "); } if (idsTwo.Count >= 1) { stringBuilder.AppendLine($" update machine set AppletS=-1 where id in ({string.Join(",", idsTwo.ConvertAll(new Converter(m => m.ToString())).ToArray())}); "); } //LogHelper.LogInfo("结束处理机台小程序运行状态---------", "EapAsync", stringBuilder.ToString()); string strsql = stringBuilder.ToString(); if (!string.IsNullOrEmpty(strsql)) { logger.LogError("修改机台运行状态: " + strsql); UpdateMachineStatus(strsql); } logger.LogError("完成处理机台小程序运行状态---------"); } #endregion Thread.Sleep(interval * 1000 * 60); //Thread.Sleep(10000); } } catch (Exception e) { logger.LogError("---------" + e.ToString()); } }); } catch (Exception ex) { var a = ex.Message; //a的值为:发生一个或多个错误。 var b = ex.GetBaseException(); //b的值为:Task异常测试 Console.WriteLine(a + "|*|" + b); errorinfo = a; } } private void UpdateMachineStatus(string strsql) { try { using (IDatabase db = DbFactory.Base("eap")) { var count = db.ExecuteBySql(strsql); } } catch (Exception ex) { logger.LogError(ex.ToString()); ; } } public int StartSingHsms(Machine row, IDatabase database) { List temp = CurrTelnet.Where(c => c.CurrMac.ID == row.ID).ToList(); if (temp.Count > 0) { int tempresult = StopSingleHsms(row); if (tempresult <= 0) return -1; } string errorinfo = ""; Telnet hsms = CreateHsms(row, ref errorinfo);// new Hsms03(row); int result = hsms.Start(database, ref errorinfo); if (result <= 0) { row.Remark = "启动失败:" + errorinfo; return -1; } row.Remark = "正常"; CurrTelnet.Add(hsms); return 1; } public Telnet CreateHsms(Machine machine, ref string errorinfo) { try { Telnet telnet = new Telnet(machine.IPAddress, 5888, 1000, logger, machine); return telnet; } catch (Exception ex) { errorinfo = ex.ToString(); return null; } } public int StopSingleHsms(Machine row) { try { string errorinfo = ""; //先在链表里找,是否已经创建该实例 List temp = CurrTelnet.Where(a => a.CurrMac.ID == row.ID).ToList(); if (temp.Count > 0) { CurrTelnet.Remove(temp[0]); } row.Remark = "停止"; return 1; } catch (Exception ex) { row.Remark = "启动失败:" + ex.Message.ToString(); return -1; } } public bool CheckIPFormat(string ip) { System.Net.IPAddress ipAddress; if (System.Net.IPAddress.TryParse(ip, out ipAddress)) { return true; } else { return false; } } } public class Telnet { private string address; private int port; private int timeout; private static readonly object obj = new object(); ILogger logger; public Machine CurrMac = new Machine();//机台数据 private Thread CheckThread = null;//检查线程 private Socket CurrSocket = null; public Telnet(string Address, int Port, int CommandTimeout, ILogger logger, Machine machine) { address = Address; port = Port; timeout = CommandTimeout; this.logger = logger; CurrMac = machine; } /// /// 启动socket 进行telnet操作 /// public bool Connect(ref string errorinfo) { try { if (CurrSocket == null) { IPAddress ip = IPAddress.Parse(address);//服务端所在IP IPEndPoint ipEnd = new IPEndPoint(ip, port);//服务端所监听的接口 CurrSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); CurrSocket.Connect(ipEnd); } else { CurrSocket.Shutdown(SocketShutdown.Both); CurrSocket.Close();//关闭Socket CurrSocket.Dispose(); CurrSocket = null; IPAddress ip = IPAddress.Parse(address);//服务端所在IP IPEndPoint ipEnd = new IPEndPoint(ip, port);//服务端所监听的接口 CurrSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); CurrSocket.Connect(ipEnd); } return true; } catch (Exception e) { errorinfo = e.ToString(); logger.LogError(errorinfo); CurrSocket = null; return false; } } public bool ConnectTcp(ref string errorinfo) { TcpClient tcpClient = null; try { tcpClient = new TcpClient(address, port); tcpClient.SendTimeout = timeout; return true; } catch (Exception ex) { logger.LogError($"TCP检查端口是否连通错误,IP地址:[{address}],错误信息:" + ex.ToString()); return false; } finally { if (tcpClient != null) { tcpClient.Close(); tcpClient.Dispose(); } } } public int Start(IDatabase database, ref string errorinfo) { StringBuilder sqlstr = new StringBuilder(100); int result = StartCheckThread(ref errorinfo); if (result <= 0) { //处理接受失败,写入数据库 sqlstr.Clear(); sqlstr.AppendFormat("{0}\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); sqlstr.AppendFormat("开始检查线程发生错误\r\n"); sqlstr.AppendFormat("{0}", errorinfo); logger.LogError(sqlstr.ToString()); return -1; } return 1; } public int StartCheckThread(ref string errorinfo) { try { //成功后,启动接受线程 CheckThread = new Thread(CheckThreadFun); CheckThread.Start(); return 1; } catch (Exception ex) { errorinfo = ex.Message.ToString(); return -1; } } private void CheckThreadFun() { try { //while (true) //{ string errorinfo = ""; using (IDatabase db = DbFactory.Base("eap")) { MachineDal machineDal = new MachineDal(db); CurrMac = machineDal.Get(CurrMac.ID); var result = Connect(ref errorinfo); if (result == true) { if (CurrMac.AppletS != 1) { string sql = $"update machine set AppletS=1 where id={CurrMac.ID};"; logger.LogError(sql); db.ExecuteBySql(sql); } Console.WriteLine(CurrMac.FCode + "已开启小程序"); logger.LogError(CurrMac.FCode + "已开启小程序"); } else { if (CurrMac.AppletS != -1) { string sql = $"update machine set AppletS=-1 where id={CurrMac.ID};"; logger.LogError(sql); db.ExecuteBySql(sql); } logger.LogError(CurrMac.FCode + "已关闭小程序"); } } Thread.Sleep(1000 * 60 * 5); //Thread.Sleep(15000); //} } catch (Exception ex) { logger.LogError(ex.ToString()); } } } }