2024-11-26 13:45:28 +08:00

105 lines
3.3 KiB
C#

using System;
using Abp;
using Microsoft.Extensions.Configuration;
using Serilog;
using Yunda.SOMS.OperationsMainSiteGatewayServer.TcpSocket.Server;
namespace Yunda.SOMS.OperationsMainSiteGatewayServer
{
public class Program
{
private static AbpBootstrapper _bootstrapper;
public static async Task Main(string[] args)
{
try
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
ConfigureLogger(configuration);
Log.Information("程序启动");
_bootstrapper = InitializeBootstrapper();
await RunApplication(ConfigureServerAddr(configuration));
Log.Information("程序运行完成");
using (var cts = new CancellationTokenSource())
{
Log.Information("主程序正在运行...");
Log.Information("按 Ctrl+C 停止程序...");
Console.CancelKeyPress += (sender, e) =>
{
e.Cancel = true; // 阻止程序立即退出
cts.Cancel(); // 触发取消
};
try
{
await Task.Delay(Timeout.Infinite, cts.Token); // 无限等待,直到取消
}
catch (TaskCanceledException)
{
Log.Information("程序停止...");
}
}
}
catch (Exception ex)
{
Log.Fatal(ex, "程序发生了致命错误");
}
finally
{
Cleanup();
}
}
/// <summary>
/// 配置日志记录器
/// </summary>
private static void ConfigureLogger(IConfigurationRoot configuration)
{
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
}
/// <summary>
/// 配置服务端addr
/// </summary>
private static byte ConfigureServerAddr(IConfigurationRoot configuration)
{
return byte.Parse(configuration["addr"].ToString());
}
/// <summary>
/// 初始化 ABP 引导程序
/// </summary>
private static AbpBootstrapper InitializeBootstrapper()
{
var bootstrapper = AbpBootstrapper.Create<OperationsGatewayAppModule>();
bootstrapper.Initialize();
return bootstrapper;
}
/// <summary>
/// 运行应用程序逻辑
/// </summary>
private static async Task RunApplication(byte addr)
{
var service = _bootstrapper.IocManager.Resolve<DotNettyTcpServer>();
await service.RunServerAsync(addr);
}
/// <summary>
/// 清理资源
/// </summary>
private static async Task Cleanup()
{
var service = _bootstrapper.IocManager.Resolve<DotNettyTcpServer>();
await service.StopSeverAsync();
_bootstrapper?.Dispose();
Log.CloseAndFlush();
}
}
}