using SunlightAggregationManager.ViewModel; using System; using System.Collections.Generic; using System.Data; using System.Security.Cryptography.Pkcs; using System.Text; using System.Text.Json; using System.Windows; using System.Windows.Markup; using System.Xml.Linq; using TouchSocket.Core; using TouchSocket.Sockets; using static SunlightAggregationManager.UserClass.AsyncTcpServer; namespace SunlightAggregationManager.UserClass { public class AsyncTcpServer { public class Person { public required string User { get; set; } public required string Password { get; set; } public required string IP { get; set; } public required string Terminal { get; set; } public required string Dat { get; set; } } public static async void Configuration(int P1, int P2) { await TcpMain(P1, P2); } public static TcpService service = new TcpService(); public static async Task TcpMain(int port1 ,int port2) { NetFwManger.AllowPort(port1, "TCP");//开放7790端口 NetFwManger.AllowPort(port2, "TCP");//开放7790端口 //TcpService service = new TcpService(); service.Connecting = (client, e) => { return EasyTask.CompletedTask; };//有客户端正在连接 service.Connected = (client, e) => {return EasyTask.CompletedTask;};//有客户端成功连接 service.Closing = (client, e) => { Console.WriteLine("[Disconnecting]IP[" + client.IP + "]ID[" + client.Id + "]"); return EasyTask.CompletedTask; };//有客户端正在断开连接,只有当主动断开时才有效。 service.Closed = (client, e) => { //离线记录 Dictionary myDictOff = new Dictionary(); myDictOff.Add("State", 15); myDictOff.Add("LastActionTime", DateTime.Now); myDictOff.Add("LastOfflineTime", DateTime.Now); myDictOff.Add("Note", "Offline"); MainWindowViewModel.Updata_Memory(MainWindowViewModel._userData, "LinkID='" + client.Id + "'", myDictOff); Console.WriteLine("[Offline]IP[" + client.IP + "]ID["+ client.Id + "]"); return EasyTask.CompletedTask; };//有客户端断开连接 service.Received = (client, e) =>{ string DAT = e.Memory.Span.ToString(Encoding.UTF8); try { Person? deserializedPerson = JsonSerializer.Deserialize(DAT); var _user = MainWindowViewModel.Selet_Memory(MainWindowViewModel._userData, "State", "User='" + deserializedPerson?.User + "' and Password ='" + deserializedPerson?.Password + "'"); if (_user != null) { string _dat = _user?.ToString() ?? "0"; if (_dat != "99") { if (_dat == "20") {//行为 Dictionary myDict = new Dictionary(); myDict.Add("LinkID", client.Id); myDict.Add("LastLoginIP", deserializedPerson?.IP ?? client.IP); myDict.Add("LastActionTime", DateTime.Now); myDict.Add("Note", deserializedPerson?.Dat ?? "unknown"); MainWindowViewModel.Updata_Memory(MainWindowViewModel._userData, "User='" + deserializedPerson?.User + "'", myDict); Console.WriteLine("[Log on]User[" + deserializedPerson?.User + "]Note[" + (deserializedPerson?.Dat ?? "unknown") + "]"); Command(deserializedPerson?.Dat ?? "NOT", client.Id, deserializedPerson!); } else {//首次登录记录 Dictionary myDict = new Dictionary(); myDict.Add("State", 20); myDict.Add("LinkID", client.Id); myDict.Add("LastLoginIP", deserializedPerson?.IP ?? client.IP); myDict.Add("LastLoginTime", DateTime.Now); myDict.Add("LastLoginTerminal", deserializedPerson?.Terminal ?? "unknown device"); myDict.Add("LastActionTime", DateTime.Now); myDict.Add("Note", deserializedPerson?.Dat ?? "unknown"); MainWindowViewModel.Updata_Memory(MainWindowViewModel._userData, "User='" + deserializedPerson?.User + "'", myDict); Console.WriteLine("[Log on]User[" + deserializedPerson?.User + "]IP[" + deserializedPerson?.IP ?? client.IP + "]ID[" + client.Id + "]Terminal[" + (deserializedPerson?.Terminal ?? "unknown device") + "]"); //返回登录信息 Dictionary login = new Dictionary(); DataRow? dat = MainWindowViewModel.Selet_Row(MainWindowViewModel._userData,"User='" + deserializedPerson?.User + "' and Password ='" + deserializedPerson?.Password + "'"); login.Add("Enterprise", dat?.Field("Enterprise")??""); login.Add("Department", dat?.Field("Department") ?? ""); login.Add("Groups", dat?.Field("Groups") ?? ""); login.Add("UserId", dat?.Field("UserID") ?? ""); login.Add("UserName", dat?.Field("Name") ?? ""); deserializedPerson!.Dat = JsonSerializer.Serialize(login); var jsdat = JsonSerializer.Serialize(deserializedPerson); client.SendAsync(jsdat); } } else {//停用账号关闭连接 client.SendAsync("Account Deactivated"); foreach (var item in AsyncTcpServer.service.Clients) { if (item.Id == client.Id) { item.CloseAsync(); //在断开连接后,释放对象。 item.Dispose(); } } } } else { //无效账号关闭连接 client.SendAsync("Invalid Account"); foreach (var item in AsyncTcpServer.service.Clients) { if (item.Id == client.Id) { item.CloseAsync(); item.Dispose(); } } } } catch (Exception ex) {//错误 LogGing.ERRDATA(ex); Console.WriteLine("Tcp:" + ex.ToString()); client.SendAsync("Target instruction parsing error manager will close connection"); foreach (var item in AsyncTcpServer.service.Clients) { if (item.Id == client.Id) { item.CloseAsync(); item.Dispose(); } } } return EasyTask.CompletedTask; }; await service.SetupAsync(new TouchSocketConfig()//载入配置 // .SetMaxBufferSize(1024 * 1024 * 100) //.SetMinBufferSize(1024 * 1024) .SetListenIPHosts(new IPHost[] { new IPHost(port1), new IPHost(port2) })//同时监听两个地址 .ConfigureContainer(a =>//容器的配置顺序应该在最前面 { }) .ConfigurePlugins(a => { }) ); await service.StartAsync();//启动 Console.WriteLine("TCP Port:"+ port1.ToString()); Console.WriteLine("TCP Port:"+ port2.ToString()); Console.WriteLine("TCP SERVER:START"); } public static async void Command(string dat,string id , Person person)// { string Command="", ret =""; Dictionary data_ = new Dictionary(); var deserialized = JsonSerializer.Deserialize>(dat)!; if (deserialized.TryGetValue("Command", out var val) && val != null) Command = val.ToString()!; if (Command == "Info")//回复info请求的信息 { var t = ToList(MainWindowViewModel._machines).ToJsonString(); //格式化返回信息 data_.Add("Info", t); ret = JsonSerializer.Serialize(data_); } if (Command == "Query")//回复Query请求的信息 { string s_ = deserialized.GetValue("StartTime").ToString()!; string e_ = deserialized.GetValue("EndTime").ToString()!; string f_ = deserialized.GetValue("Field").ToString()!; DataTable resultTable = await MainWindowViewModel.dataBase.ExecuteQueryAsync("SELECT "+ f_+" FROM [dbo].[Dyelots] " + "WHERE CreationTime>'"+s_+"'and CreationTime<'"+e_+"'"); //格式化返回信息 data_.Add("Query", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable)); ret = JsonSerializer.Serialize(data_); } if (Command == "QueryDyelot")//回复QueryDyelot请求的信息 { string d_ = deserialized.GetValue("DyelotName").ToString()!; string f_ = deserialized.GetValue("Field").ToString()!; DataTable resultTable = await MainWindowViewModel.dataBase.ExecuteQueryAsync("SELECT " + f_ + " FROM [dbo].[Dyelots] " + "WHERE Dyelot LIKE '" + d_ + "%'"); //格式化返回信息 data_.Add("Query", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable)); ret = JsonSerializer.Serialize(data_); } if (Command == "QueryDetail")//回复info请求的信息 { string d_ = deserialized.GetValue("Dyelot").ToString()!; string r_ = deserialized.GetValue("ReDye").ToString()!; string f_ = deserialized.GetValue("Field").ToString()!; DataTable resultTable = await MainWindowViewModel.dataBase.ExecuteQueryAsync("SELECT " + f_ + " FROM [dbo].[DyelotsBulkedRecipe] " + "WHERE Dyelot='" + d_ + "'and ReDye='" + r_ + "'"); //格式化返回信息 data_.Add("QueryDetail", Newtonsoft.Json.JsonConvert.SerializeObject(resultTable)); ret = JsonSerializer.Serialize(data_); } person.Dat=ret.ToString(); var jsdat = JsonSerializer.Serialize(person); await service.SendAsync(id, jsdat); } public static List>? ToList(DataTable table)//datatable转list { if (table == null) return null; // 使用 AsEnumerable() 将 DataTable 转换为 IEnumerable // 然后投影为 Dictionary return table.AsEnumerable().Select(row => table.Columns.Cast().ToDictionary( col => col.ColumnName, col => { var value = row[col]; // 核心修改:如果是数据库空值 DBNull.Value,则转为 C# 的 null,否则保持原值 return value == DBNull.Value ? null : value; } ) ).ToList(); } } }