添加刷新逻辑

This commit is contained in:
Administrator committed 2026-08-03 15:36:47 +08:00
1 parent f40e9db080
commit dcfa96824f
13 files changed
+875

No files matched your search

+157
View File
@@ -0,0 +1,157 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Windows;
using System.Xml.Linq;
using TouchSocket.Core;
using TouchSocket.Http;
using TouchSocket.Http.WebSockets;
using TouchSocket.Sockets;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace ForwardingServerUI.Class
{
public class AsyncHttpServer
{
public static HttpService httpservice = new HttpService();
public static async Task HttpMain()
{
await httpservice.SetupAsync(new TouchSocketConfig()//加载配置
.SetListenIPHosts(7791)
.ConfigureContainer(a =>
{
a.AddConsoleLogger();
})
.ConfigurePlugins(a =>
{
a.Add<MyHttpPlug1>();
//default插件应该最后添加,其作用是
//1、为找不到的路由返回404
//2、处理 header 为Option的探视跨域请求。
a.UseDefaultHttpServicePlugin();
}));
await httpservice.StartAsync();
Console.WriteLine("HttpService:Run");
}
public class MyHttpPlug1 : PluginBase, IHttpPlugin
{
public async Task OnHttpRequest(IHttpSessionClient client, HttpContextEventArgs e)
{
#region HttpContext生命周期
//var request = e.Context.Request;//http请求体
var response = e.Context.Response;//http响应体
#endregion
var bodyString = await e.Context.Request.GetBodyAsync();
//获取路径
var URL = e.Context.Request.URL;
try
{
string dat;
DataRow[] rows = MainWindowViewModel._machineTable.Select("Enterprise='/" + URL + "'");
if (rows.Length > 0)
{
string? s_ = rows.First().Field<string?>("ID")!;
if (s_ != null)
{
// var deserialized = JsonSerializer.Deserialize<Dictionary<string, object>>(bodyString)!;
// if (deserialized.TryGetValue("Terminal", out var val) && val != null) { }
// using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
await AsyncTcpServer.service.SendAsync(s_, bodyString);
MainWindowViewModel.Person deserializedPerson = JsonSerializer.Deserialize<MainWindowViewModel.Person>(bodyString)!;
Application.Current.Dispatcher.Invoke(() => {
MainWindowViewModel._userTable.Rows.Add(client.Id, client.IP, deserializedPerson.User,
"", deserializedPerson.Terminal, "", "");
});
// 创建一个 秒的延时任务
Task delayTask = Task.Delay(15000);
// 创建一个监测任务,不断检查变量
Task monitorTask = Task.Run(async () =>
{
while (!(MainWindowViewModel._userTable.Select("Terminal='" + deserializedPerson.Terminal + "'").
First().Field<string>("RDAT")!.Length > 1))
{
await Task.Delay(500);
}
});
Task winner = await Task.WhenAny(delayTask, monitorTask);
DataRow[] dataRows = MainWindowViewModel._userTable.Select("Terminal='" + deserializedPerson.Terminal + "'");
if (winner == monitorTask)
{
dat = dataRows.First().Field<string>("RDAT")!;
}
else { dat = "970"; }
foreach (DataRow row in dataRows)
{
Application.Current.Dispatcher.Invoke(() => {
MainWindowViewModel._userTable.Rows.Remove(row);
});
}
}
else { dat = "999"; }
}
else
{
dat = "980";
}
e.Context.Response.Headers.Add("SUNLIGHT", "SUNLIGHT");
e.Context.Response.SetStatus(200, "success");
e.Context.Response.SetContent(Encoding.UTF8.GetBytes(dat.ToCharArray()));
await e.Context.Response.AnswerAsync();
}
catch (TimeoutException)
{
Console.WriteLine("等待TCP服务端响应超时");
}
catch (Exception ex)
{//错误
Console.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-DD HH:mm:ss:fff") + "] Http:" + ex.ToString());
LogGing.ERRDATA(ex);
//client.SendAsync("Target instruction parsing error manager will close connection");
}
/* if (request.IsGet() && request.UrlEquals("/success"))
{
//直接响应文字
await response
.SetStatus(200, "success")
.FromText("Success")
.AnswerAsync();//直接回应
Console.WriteLine("处理/success");
return;
}
//无法处理,调用下一个插件
await e.InvokeNext();*/
}
}
}
}
+137
View File
@@ -0,0 +1,137 @@
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 System.Runtime.InteropServices.JavaScript.JSType;
namespace ForwardingServerUI.Class
{
public class AsyncTcpServer
{
public class Personm
{
public required string SERVEREnterprise { get; set; }
public required string SERVERMachineName { get; set; }
public required string SERVERNAME { get; set; }
public required string SERVERUSER { get; set; }
public required string SERRVERPASWORD { get; set; }
public required string MachineVer { get; set; }
}
public static TcpService service = new TcpService();
public static async Task TcpMain()
{
//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) => {
//离线记录
DataRow[] dat = MainWindowViewModel._machineTable.Select("ID='"+client.Id+"'");
foreach (DataRow row in dat)
{
Application.Current.Dispatcher.Invoke(() => {
MainWindowViewModel._machineTable.Rows.Remove(row);
});
}
Console.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-DD HH:mm:ss:fff") + "] NOT ID " + client.Id + " IP " + client.IP);
return EasyTask.CompletedTask;
};//有客户端断开连接
service.Received = (client, e) =>{
string DAT = e.Memory.Span.ToString(Encoding.UTF8);
try
{
if (DAT.Length > 5)
{
DataRow[] r_ = MainWindowViewModel._machineTable.Select("ID='" + client.Id + "'");
if (r_.Length > 0)
{
int? s_ = r_.First().Field<int?>("Start");
if (s_ == 30)
{
if (DAT.StartsWith("{") || DAT.StartsWith("["))
{
MainWindowViewModel.Person deserializedPerson = JsonSerializer.Deserialize<MainWindowViewModel.Person>(DAT)!;
//转发逻辑
var dr = MainWindowViewModel._userTable.Select("Terminal='" + deserializedPerson.Terminal + "'");
if (dr.Length > 0)
{
DataRow drEmployee = dr.First();
drEmployee.BeginEdit();
drEmployee["RDAT"] = DAT;
drEmployee.EndEdit();
drEmployee.AcceptChanges();
}
}
}
}
else
{
Personm deserializedPerson = JsonSerializer.Deserialize<Personm>(DAT)!;
Application.Current.Dispatcher.Invoke(() => {
var mach = MainWindowViewModel._machineTable.Select("Enterprise='" + deserializedPerson.SERVEREnterprise +
"'and MachineName='" + deserializedPerson.SERVERMachineName + "'");
if (mach.Length > 0)
{
DataRow dataRow = mach.First();
dataRow.BeginEdit();
dataRow["ID"] = client.Id;
dataRow["IP"] = client.IP;
dataRow["Start"] = 30;
dataRow["Enterprise"] = "/" + deserializedPerson.SERVEREnterprise;
dataRow["MachineName"] = deserializedPerson.SERVERMachineName;
dataRow["MachineVer"] = deserializedPerson.MachineVer;
dataRow.EndEdit();
dataRow.AcceptChanges();
}
else
{
MainWindowViewModel._machineTable.Rows.Add(client.Id, client.IP, 30, "/" + deserializedPerson.SERVEREnterprise,
deserializedPerson.SERVERMachineName, deserializedPerson.MachineVer);
}
});
Console.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-DD HH:mm:ss:fff") + " [LINK ID " + client.Id + " IP " + client.IP + "]\nDATA =" + DAT);
}
}
}
catch (Exception ex)
{//错误
Console.WriteLine("Tcp:" + ex.ToString());
LogGing.ERRDATA(ex);
}
return EasyTask.CompletedTask;
};
await service.SetupAsync(new TouchSocketConfig()//载入配置
// .SetMaxBufferSize(1024 * 1024 * 100)
//.SetMinBufferSize(1024 * 1024)
.SetSingleStreamDataHandlingAdapter(() => new PeriodPackageAdapter())//以超时周期和包
.SetListenIPHosts(new IPHost[] { new IPHost(7794), new IPHost(7795) })//同时监听两个地址
.ConfigureContainer(a =>//容器的配置顺序应该在最前面
{
})
.ConfigurePlugins(a =>
{
})
);
await service.StartAsync();//启动
Console.WriteLine("TcpServer:Run");
}
}
}
+142
View File
@@ -0,0 +1,142 @@
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using TouchSocket.Core;
using TouchSocket.Http;
using TouchSocket.Http.WebSockets;
using TouchSocket.Sockets;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace ForwardingServerUI.Class
{
public class AsyncWebSocketServer
{
public static HttpService service = new HttpService();
public static async Task WebSocketMain()
{
//var service = new HttpService();
var config = new TouchSocketConfig();
config.SetListenIPHosts(7792)
.ConfigureContainer(a =>
{
a.AddConsoleLogger();
})
.ConfigurePlugins(a =>
{
//添加WebSocket功能
a.UseWebSocket(options =>
{
options.SetVerifyConnection(async (client, context) =>
{
if (!context.Request.IsUpgrade())
{
//如果不包含升级协议的header,就直接返回false。
return false;
}
// 在此处添加验证逻辑,例如:匹配特定的URL
if (true) // context.Request.UrlEquals("/ws"))
{
var url = context.Request.URL;
return true; // 允许连接
}
//如果url不匹配,则可以直接拒绝。
//await context.Response
//.SetStatus(403, "url不正确")
//.AnswerAsync();
return false;
});
});
a.Add<MyWebSocketReceivePlugin>();
a.Add<MyWebSocketClosedPlugin>();
});
//加载配置
await service.SetupAsync(config);
//启动服务
await service.StartAsync();
Console.WriteLine("WebSocketService:Run");
}
public async Task WebSocketSendAsync(string id,string dat) {
var clients = service.Clients;
foreach (var client in clients)
{
if (client.Protocol == Protocol.WebSocket)//先判断是不是websocket协议
{
if (client.Id == id)//再按指定id发送,或者直接广播发送
{
var webSocket = client.WebSocket;
await webSocket.SendAsync(dat);
}
}
}
}
private class MyWebSocketClosedPlugin : PluginBase, IWebSocketClosedPlugin
{
public async Task OnWebSocketClosed(IWebSocket webSocket, ClosedEventArgs e)
{
var ClientId = (webSocket as IIdClient)!.Id;
}
}
private class MyWebSocketReceivePlugin : PluginBase, IWebSocketReceivedPlugin
{
public async Task OnWebSocketReceived(IWebSocket webSocket, WSDataFrameEventArgs e)
{
//处理接收的数据
var dataFrame = e.DataFrame;
switch (dataFrame.Opcode)
{
case WSDataType.Cont:
//处理中继包
break;
case WSDataType.Text:
//处理文本包
Console.WriteLine(dataFrame.ToText());
break;
case WSDataType.Binary:
//处理二进制包
var data = dataFrame.PayloadData;
Console.WriteLine($"收到二进制数据,长度:{data.Length}");
break;
case WSDataType.Close:
//处理关闭包
break;
case WSDataType.Ping:
//处理Ping包
break;
case WSDataType.Pong:
//处理Pong包
break;
default:
//处理其他包
break;
}
await e.InvokeNext();
}
}
}
}
+118
View File
@@ -0,0 +1,118 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
namespace ForwardingServerUI.Class
{
public class LogGing
{
public static void LogGingDATA(string dat)
{
string logpath = System.Environment.CurrentDirectory + "\\Log";//日志文件目录
string logPath = "" + System.Environment.CurrentDirectory + "\\Log\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";//日志文件
string Log_time = "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]:";
if (Directory.Exists(logpath))//检查日志路径
{
if (!File.Exists(logPath))//检查日志文件并写入启动日志
{
FileStream fs = new FileStream(logPath, FileMode.CreateNew, FileAccess.Write);//创建写入文件
StreamWriter wr = new StreamWriter(fs);//创建文件
wr.WriteLine(Log_time + dat);
wr.Close();
}
else
{
try
{
FileStream fs = new FileStream(logPath, FileMode.Append, FileAccess.Write);
StreamWriter wr = new StreamWriter(fs);//创建文件
wr.WriteLine(Log_time + dat);
wr.Close();
}
catch { }
}
}
else
{
DirectoryInfo directoryInfo = new DirectoryInfo(logpath);
directoryInfo.Create();//创建日志路径
}
}
public static void ERRDATA(System.Exception dat)
{
string Log_time = DateTime.Now.ToString("yyyy-MM-dd");
string logpath = System.Environment.CurrentDirectory + "\\ERR";//日志文件目录
// string logPathtxt = "" + System.Environment.CurrentDirectory + "\\Log\\"+ Log_time + "Log.txt";//日志文件
// System.IO.DirectoryInfo log = new System.IO.DirectoryInfo();//生成日志文件目录
string log_path = logpath + "\\ERR" + Log_time + ".txt";
string Log_timehms = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
if (Directory.Exists(logpath))//检查日志路径
{
if (!File.Exists(log_path))//检查文件并写入
{
// FileStream fs = new FileStream(log_path, FileMode.CreateNew, FileAccess.Write);//创建文件
// StreamWriter wr = new StreamWriter(fs);//创建文件
// wr.Close();
FileStream fil = new FileStream(log_path, FileMode.CreateNew, FileAccess.Write);//创建写入文件
StreamWriter wfil = new StreamWriter(fil);//创建文件
wfil.WriteLine("[" + Log_timehms + "];[Error] ||" + Environment.NewLine.ToString());
wfil.WriteLine("[" + Log_timehms + "];[Error source] ||" + dat.Source.ToString() + Environment.NewLine.ToString());
wfil.WriteLine("[" + Log_timehms + "];[Error message] ||" + dat.Message.ToString() + Environment.NewLine.ToString());
wfil.WriteLine("[" + Log_timehms + "];[Error area] ||" + dat.StackTrace.ToString());
wfil.Close();
}
else
{
FileStream fs = new FileStream(log_path, FileMode.Append, FileAccess.Write);//创建写入文件
StreamWriter wr = new StreamWriter(fs);//创建文件
wr.WriteLine("[" + Log_timehms + "];[Error] ||" + Environment.NewLine.ToString());
wr.WriteLine("[" + Log_timehms + "];[Error source] ||" + dat.ToString() + Environment.NewLine.ToString());
wr.WriteLine("[" + Log_timehms + "];[Error message] ||" + dat.Message.ToString() + Environment.NewLine.ToString());
wr.WriteLine("[" + Log_timehms + "];[Error area] ||" + dat.ToString());
wr.Close();
}
}
else
{
DirectoryInfo directoryInfo = new DirectoryInfo(logpath);
directoryInfo.Create();
}
}
public static void ExchangeDATA(string dat)
{
string Log_time = DateTime.Now.ToString("yyyy-MM-dd");
string logpath = System.Environment.CurrentDirectory + "\\Exchange";//日志文件目录
// string logPathtxt = "" + System.Environment.CurrentDirectory + "\\Log\\"+ Log_time + "Log.txt";//日志文件
// System.IO.DirectoryInfo log = new System.IO.DirectoryInfo();//生成日志文件目录
string log_path = logpath + "\\Exchange" + Log_time + ".txt";
string Log_timehms = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
if (Directory.Exists(logpath))//检查日志路径
{
if (!File.Exists(log_path))//检查文件并写入
{
// FileStream fs = new FileStream(log_path, FileMode.CreateNew, FileAccess.Write);//创建文件
// StreamWriter wr = new StreamWriter(fs);//创建文件
// wr.Close();
FileStream fil = new FileStream(log_path, FileMode.CreateNew, FileAccess.Write);//创建写入文件
StreamWriter wfil = new StreamWriter(fil);//创建文件
wfil.WriteLine("[" + Log_timehms + "];[Exchange] ||" + dat);
wfil.Close();
}
else
{
FileStream fs = new FileStream(log_path, FileMode.Append, FileAccess.Write);//创建写入文件
StreamWriter wr = new StreamWriter(fs);//创建文件
wr.WriteLine("[" + Log_timehms + "];[Exchange] ||" + dat);
wr.Close();
}
}
else
{
DirectoryInfo directoryInfo = new DirectoryInfo(logpath);
directoryInfo.Create();
}
}
}
}
+69
View File
@@ -0,0 +1,69 @@
using System;
using System.IO;
using System.Text;
using System.Windows; // WPF 的核心命名空间
using System.Windows.Controls; // WPF TextBox 所在的命名空间
using System.Windows.Threading; // 用于 Dispatcher
namespace ForwardingServerUI.Class
{
public class ControlWriter : TextWriter
{
private readonly TextBox _textbox;
private readonly Action<string> _logGingDataAction;
public ControlWriter(TextBox textbox,Action<string> logGingDataAction)
{
_textbox = textbox;
_logGingDataAction = logGingDataAction;
}
public override void Write(char value) => AppendText(DateTime.Now + ": " + value.ToString(), true);
public override void Write(string? value) => AppendText(DateTime.Now + ": " + value, true);
public override void WriteLine(string? value) => AppendText(DateTime.Now + ": "+value + Environment.NewLine, true);
private void AppendText(string text, bool invokeExternalLog)
{
if (!_textbox.Dispatcher.CheckAccess())
{
_textbox.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() => AppendText(text, true)));
return;
}
_textbox.AppendText(text);
_textbox.ScrollToEnd();
if (invokeExternalLog)
{
_logGingDataAction?.Invoke(text);
}
}
public override Encoding Encoding => Encoding.UTF8;
}
//全局日志管理器
public static class GlobalLogManager
{
private static ControlWriter? _currentWriter;
// 【核心功能】注册目标 TextBox
// 子页面加载时调用这个方法
public static void RegisterTarget(TextBox logBox ,Action<string> logGingDataAction)
{
// 创建新的 Writer
_currentWriter = new ControlWriter(logBox, logGingDataAction);
// 【关键】将 Console 的输出重定向到这个 Writer
// 这样 Console.WriteLine("...") 就会自动写入到 logBox 中
Console.SetOut(_currentWriter);
Console.WriteLine("Start");
}
//提供一个直接写入的方法(如果不使用 Console.WriteLine)
public static void Write(string message)
{
_currentWriter?.WriteLine(message);
}
}
}