13 changed files with 856 additions and 0 deletions
@ -0,0 +1,9 @@ |
|||||
|
<Application x:Class="ForwardingServerUI.App" |
||||
|
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" |
||||
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" |
||||
|
xmlns:local="clr-namespace:ForwardingServerUI" |
||||
|
StartupUri="MainWindow.xaml"> |
||||
|
<Application.Resources> |
||||
|
|
||||
|
</Application.Resources> |
||||
|
</Application> |
||||
@ -0,0 +1,14 @@ |
|||||
|
using System.Configuration; |
||||
|
using System.Data; |
||||
|
using System.Windows; |
||||
|
|
||||
|
namespace ForwardingServerUI |
||||
|
{ |
||||
|
/// <summary>
|
||||
|
/// Interaction logic for App.xaml
|
||||
|
/// </summary>
|
||||
|
public partial class App : Application |
||||
|
{ |
||||
|
} |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,10 @@ |
|||||
|
using System.Windows; |
||||
|
|
||||
|
[assembly: ThemeInfo( |
||||
|
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
|
||||
|
//(used if a resource is not found in the page,
|
||||
|
// or application resource dictionaries)
|
||||
|
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
|
||||
|
//(used if a resource is not found in the page,
|
||||
|
// app, or any theme specific resource dictionaries)
|
||||
|
)] |
||||
@ -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();*/ |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
|
||||
|
|
||||
|
|
||||
|
|
||||
|
|
||||
|
|
||||
|
|
||||
|
|
||||
|
|
||||
|
|
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,118 @@ |
|||||
|
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(() => { |
||||
|
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"); |
||||
|
} |
||||
|
|
||||
|
} |
||||
|
} |
||||
@ -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(); |
||||
|
} |
||||
|
|
||||
|
} |
||||
|
|
||||
|
|
||||
|
} |
||||
|
} |
||||
@ -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(); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -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); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,17 @@ |
|||||
|
<Project Sdk="Microsoft.NET.Sdk"> |
||||
|
|
||||
|
<PropertyGroup> |
||||
|
<OutputType>WinExe</OutputType> |
||||
|
<TargetFramework>net10.0-windows</TargetFramework> |
||||
|
<Nullable>enable</Nullable> |
||||
|
<ImplicitUsings>enable</ImplicitUsings> |
||||
|
<UseWPF>true</UseWPF> |
||||
|
</PropertyGroup> |
||||
|
|
||||
|
<ItemGroup> |
||||
|
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.2" /> |
||||
|
<PackageReference Include="TouchSocket" Version="4.2.16" /> |
||||
|
<PackageReference Include="TouchSocket.Http" Version="4.2.16" /> |
||||
|
</ItemGroup> |
||||
|
|
||||
|
</Project> |
||||
@ -0,0 +1,3 @@ |
|||||
|
<Solution> |
||||
|
<Project Path="ForwardingServerUI.csproj" /> |
||||
|
</Solution> |
||||
@ -0,0 +1,109 @@ |
|||||
|
<Window x:Class="ForwardingServerUI.MainWindow" |
||||
|
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" |
||||
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" |
||||
|
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" |
||||
|
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" |
||||
|
xmlns:local="clr-namespace:ForwardingServerUI" |
||||
|
mc:Ignorable="d" |
||||
|
xmlns:viewmodel="clr-namespace:ForwardingServerUI" |
||||
|
d:DataContext="{d:DesignInstance Type=viewmodel:MainWindowViewModel}" |
||||
|
Loaded="Window_Loaded" |
||||
|
Title="MainWindow" Height="800" Width="900"> |
||||
|
<Grid> |
||||
|
<Grid.RowDefinitions> |
||||
|
<RowDefinition/> |
||||
|
<RowDefinition Height="5"/> |
||||
|
<RowDefinition/> |
||||
|
<RowDefinition Height="400"/> |
||||
|
</Grid.RowDefinitions> |
||||
|
<DataGrid Grid.Row="0" x:Name="DataGridmachines" |
||||
|
ItemsSource="{Binding MachineTable.DefaultView}" |
||||
|
SelectionMode="Single" |
||||
|
AlternationCount="2" |
||||
|
IsReadOnly="True" |
||||
|
FontSize="16" |
||||
|
Margin="5,5,5,5" |
||||
|
MinColumnWidth="30" |
||||
|
HorizontalGridLinesBrush="#FFC9C9C9" |
||||
|
VerticalGridLinesBrush="#FFC9C9C9" |
||||
|
GridLinesVisibility="All" |
||||
|
BorderBrush="#CCCCCC" |
||||
|
HorizontalContentAlignment="Right" |
||||
|
VerticalContentAlignment="Center"> |
||||
|
<DataGrid.RowStyle > |
||||
|
<Style TargetType="{x:Type DataGridRow}"> |
||||
|
<Style.Triggers> |
||||
|
<Trigger Property="ItemsControl.AlternationIndex" Value="0"> |
||||
|
<Setter Property="Background" Value="#FFFFFFFF" /> |
||||
|
<Setter Property="Height" Value="40" /> |
||||
|
</Trigger> |
||||
|
<Trigger Property="ItemsControl.AlternationIndex" Value="1"> |
||||
|
<Setter Property="Background" Value="#FFF0F0F0" /> |
||||
|
<Setter Property="Height" Value="40" /> |
||||
|
</Trigger> |
||||
|
<Trigger Property="IsMouseOver" Value="False"> |
||||
|
</Trigger> |
||||
|
</Style.Triggers> |
||||
|
</Style> |
||||
|
</DataGrid.RowStyle> |
||||
|
<DataGrid.CellStyle> |
||||
|
<Style TargetType="DataGridCell"> |
||||
|
<Setter Property="BorderThickness" Value="0"/> |
||||
|
<Setter Property="MinWidth" Value="20"/> |
||||
|
<Style.Triggers> |
||||
|
<Trigger Property="IsSelected" Value="True"> |
||||
|
<Setter Property="Background" Value="#FFC0C0C0"/> |
||||
|
<Setter Property="BorderBrush" Value="#FFC0C0C0"/> |
||||
|
<Setter Property="Foreground" Value="#000000"/> |
||||
|
</Trigger> |
||||
|
</Style.Triggers> |
||||
|
</Style> |
||||
|
</DataGrid.CellStyle> |
||||
|
</DataGrid> |
||||
|
<DataGrid Grid.Row="2" |
||||
|
ItemsSource="{Binding UserTable.DefaultView}" |
||||
|
SelectionMode="Single" |
||||
|
AlternationCount="2" |
||||
|
IsReadOnly="True" |
||||
|
FontSize="16" |
||||
|
Margin="5,5,5,5" |
||||
|
MinColumnWidth="30" |
||||
|
HorizontalGridLinesBrush="#FFC9C9C9" |
||||
|
VerticalGridLinesBrush="#FFC9C9C9" |
||||
|
GridLinesVisibility="All" |
||||
|
BorderBrush="#CCCCCC" |
||||
|
HorizontalContentAlignment="Right" |
||||
|
VerticalContentAlignment="Center"> |
||||
|
<DataGrid.RowStyle > |
||||
|
<Style TargetType="{x:Type DataGridRow}"> |
||||
|
<Style.Triggers> |
||||
|
<Trigger Property="ItemsControl.AlternationIndex" Value="0"> |
||||
|
<Setter Property="Background" Value="#FFFFFFFF" /> |
||||
|
<Setter Property="Height" Value="40" /> |
||||
|
</Trigger> |
||||
|
<Trigger Property="ItemsControl.AlternationIndex" Value="1"> |
||||
|
<Setter Property="Background" Value="#FFF0F0F0" /> |
||||
|
<Setter Property="Height" Value="40" /> |
||||
|
</Trigger> |
||||
|
<Trigger Property="IsMouseOver" Value="False"> |
||||
|
</Trigger> |
||||
|
</Style.Triggers> |
||||
|
</Style> |
||||
|
</DataGrid.RowStyle> |
||||
|
<DataGrid.CellStyle> |
||||
|
<Style TargetType="DataGridCell"> |
||||
|
<Setter Property="BorderThickness" Value="0"/> |
||||
|
<Setter Property="MinWidth" Value="20"/> |
||||
|
<Style.Triggers> |
||||
|
<Trigger Property="IsSelected" Value="True"> |
||||
|
<Setter Property="Background" Value="#FFC0C0C0"/> |
||||
|
<Setter Property="BorderBrush" Value="#FFC0C0C0"/> |
||||
|
<Setter Property="Foreground" Value="#000000"/> |
||||
|
</Trigger> |
||||
|
</Style.Triggers> |
||||
|
</Style> |
||||
|
</DataGrid.CellStyle> |
||||
|
</DataGrid> |
||||
|
<TextBox Grid.Row="6" x:Name="LOG" TextWrapping="Wrap" FontSize="16"/> |
||||
|
</Grid> |
||||
|
</Window> |
||||
@ -0,0 +1,34 @@ |
|||||
|
using ForwardingServerUI.Class; |
||||
|
using System.Collections.ObjectModel; |
||||
|
using System.Data; |
||||
|
using System.Text; |
||||
|
using System.Windows; |
||||
|
using System.Windows.Controls; |
||||
|
using System.Windows.Data; |
||||
|
using System.Windows.Documents; |
||||
|
using System.Windows.Input; |
||||
|
using System.Windows.Media; |
||||
|
using System.Windows.Media.Imaging; |
||||
|
using System.Windows.Navigation; |
||||
|
using System.Windows.Shapes; |
||||
|
|
||||
|
namespace ForwardingServerUI |
||||
|
{ |
||||
|
/// <summary>
|
||||
|
/// Interaction logic for MainWindow.xaml
|
||||
|
/// </summary>
|
||||
|
public partial class MainWindow : Window |
||||
|
{ |
||||
|
public MainWindow() |
||||
|
{ |
||||
|
InitializeComponent(); |
||||
|
DataContext = new MainWindowViewModel(); |
||||
|
} |
||||
|
|
||||
|
private void Window_Loaded(object sender, RoutedEventArgs e) |
||||
|
{ |
||||
|
GlobalLogManager.RegisterTarget(LOG, LogGing.LogGingDATA); |
||||
|
|
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,56 @@ |
|||||
|
using CommunityToolkit.Mvvm; |
||||
|
using CommunityToolkit.Mvvm.ComponentModel; |
||||
|
using CommunityToolkit.Mvvm.Input; |
||||
|
using ForwardingServerUI.Class; |
||||
|
using System; |
||||
|
using System.Collections.Generic; |
||||
|
using System.Data; |
||||
|
using System.Text; |
||||
|
|
||||
|
namespace ForwardingServerUI |
||||
|
{ |
||||
|
public partial class MainWindowViewModel : ObservableObject |
||||
|
{ |
||||
|
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; } |
||||
|
} |
||||
|
|
||||
|
[ObservableProperty] |
||||
|
public static DataTable _machineTable = new(); |
||||
|
[ObservableProperty] |
||||
|
public static DataTable _userTable = new(); |
||||
|
|
||||
|
public async void Data() |
||||
|
{ |
||||
|
_machineTable.Columns.Add("ID", typeof(string)); |
||||
|
_machineTable.Columns.Add("IP", typeof(string)); |
||||
|
_machineTable.Columns.Add("Start", typeof(int)); |
||||
|
_machineTable.Columns.Add("Enterprise", typeof(string)); |
||||
|
_machineTable.Columns.Add("MachineName", typeof(string)); |
||||
|
_machineTable.Columns.Add("MachineVer", typeof(string)); |
||||
|
|
||||
|
|
||||
|
_userTable.Columns.Add("ID", typeof(string)); |
||||
|
_userTable.Columns.Add("IP", typeof(string)); |
||||
|
_userTable.Columns.Add("User", typeof(string)); |
||||
|
_userTable.Columns.Add("Enterprise", typeof(string)); |
||||
|
_userTable.Columns.Add("Terminal", typeof(string)); |
||||
|
_userTable.Columns.Add("MachineName", typeof(string)); |
||||
|
_userTable.Columns.Add("RDAT", typeof(string)); |
||||
|
|
||||
|
await AsyncTcpServer.TcpMain(); |
||||
|
await AsyncHttpServer.HttpMain(); |
||||
|
} |
||||
|
|
||||
|
|
||||
|
public MainWindowViewModel() |
||||
|
{ |
||||
|
Data(); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
Loading…
Reference in new issue