整合管理器服务端
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.

225 lines
10 KiB

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.Xml.Linq;
using TouchSocket.Core;
using TouchSocket.Sockets;
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 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) => { return EasyTask.CompletedTask; };//有客户端正在断开连接,只有当主动断开时才有效。
service.Closed = (client, e) => {
//离线记录
Dictionary<string, object> myDictOff = new Dictionary<string, object>();
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<Person>(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<string, object> myDict = new Dictionary<string, object>();
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") + "]");
}
else
{//首次登录记录
Dictionary<string, object> myDict = new Dictionary<string, object>();
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<string, object> login = new Dictionary<string, object>();
DataRow? dat = MainWindowViewModel.Selet_Row(MainWindowViewModel._userData,"User='" +
deserializedPerson?.User + "' and Password ='" + deserializedPerson?.Password + "'");
login.Add("Enterprise", dat?.Field<object>("Enterprise")??"");
login.Add("Department", dat?.Field<object>("Department") ?? "");
login.Add("Groups", dat?.Field<object>("Groups") ?? "");
login.Add("UserId", dat?.Field<object>("UserID") ?? "");
login.Add("UserName", dat?.Field<object>("Name") ?? "");
var d = JsonSerializer.Serialize(login);
client.SendAsync(d);
}
}
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)
{//错误
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();
}
}
}
//string DAT = e.ByteBlock.Span.ToString(Encoding.UTF8).Substring(5);
//string SYSDAT = "";// = e.ByteBlock.Span.ToString(Encoding.ASCII).Substring(5);
// string SYSKEY = "";
// if (DAT.Length >= 16) SYSKEY = DAT.Substring(0, 16);
// if (DAT.Length > 16) SYSDAT = DAT.Substring(16);
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");
}
}
class MyTcpService : TcpService<MyTcpSessionClient>
{
protected override MyTcpSessionClient NewClient()
{
return new MyTcpSessionClient();
}
}
class MyTcpSessionClient : TcpSessionClient
{
internal void SetDataHandlingAdapter(SingleStreamDataHandlingAdapter adapter)
{
base.SetAdapter(adapter);
}
}
/// <summary>
/// 此插件实现,按照不同端口,使用不同适配器。
/// <list type="bullet">
/// <item>7789端口:使用"**"结尾的数据</item>
/// <item>7790端口:使用"##"结尾的数据</item>
/// </list>
/// </summary>
internal class DifferentProtocolPlugin : PluginBase, ITcpConnectingPlugin, ITcpReceivedPlugin
{
public async Task OnTcpConnecting(ITcpSession client, ConnectingEventArgs e)
{
if (client is MyTcpSessionClient sessionClient)
{
if (sessionClient.ServicePort == 7789)
{
sessionClient.SetDataHandlingAdapter(new TerminatorPackageAdapter("**"));
}
else
{
sessionClient.SetDataHandlingAdapter(new TerminatorPackageAdapter("##"));
}
}
await e.InvokeNext();
}
public async Task OnTcpReceived(ITcpSession client, ReceivedDataEventArgs e)
{
//如果是自定义适配器,此处解析时,可以判断e.RequestInfo的类型
if (client is ITcpSessionClient sessionClient)
{
sessionClient.Logger.Info($"{sessionClient.GetIPPort()}收到数据,服务器端口:{sessionClient.ServicePort},数据:{e.Memory.Span.ToString(Encoding.UTF8)}");
}
await e.InvokeNext();
}
}
}