-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
123 lines (102 loc) · 4.62 KB
/
Program.cs
File metadata and controls
123 lines (102 loc) · 4.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Network.Adapters;
using Network.Core.Application.Loop;
using Network.Core.Application.Options;
using Network.Core.Application.Ports.Inbound;
using Network.Core.Application.Ports.Outbound;
using NetworkExample.Console.Packets;
namespace NetworkExample.Console;
public class Program
{
static async Task Main(string[] args)
{
System.Console.WriteLine("NetworkHexagonal - Demo de Chat");
System.Console.WriteLine("-----------------------------");
if (args.Length == 0 || args[0] == "-h" || args[0] == "--help" || (args[0] != "server" && args[0] != "client"))
{
System.Console.WriteLine("Uso: dotnet run -- [server|client]");
return;
}
string mode = args[0].ToLower();
string username = "Player"; // Default
if (mode == "client")
{
System.Console.Write("Digite seu nome de usuário: ");
username = System.Console.ReadLine() ?? "Player";
}
// --- Configuração da Injeção de Dependência ---
var services = new ServiceCollection();
IConfiguration configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables()
.AddCommandLine(args)
.Build();
services.AddSingleton(configuration);
services.Configure<NetworkOptions>(configuration.GetSection(NetworkOptions.SectionName));
services.AddSingleton<NetworkOptions>(sp => sp.GetRequiredService<IOptions<NetworkOptions>>().Value);
services.Configure<LoopOptions>(configuration.GetSection(LoopOptions.SectionName));
services.AddSingleton<LoopOptions>(sp => sp.GetRequiredService<IOptions<LoopOptions>>().Value);
services.AddLogging(builder =>
{
builder.AddConfiguration(configuration.GetSection("Logging"));
builder.AddConsole();
});
if (mode == "server")
services.AddServerNetworking();
else if (mode == "client")
services.AddClientNetworking();
services.AddGameLoopIntegration()
.AddGameService<NetworkLoopAdapter>();
services.AddSingleton(sp => new ConsoleChatManager(
mode,
username,
sp.GetRequiredService<IPacketSender>(),
sp.GetRequiredService<INetworkEventBus>()
));
services.AddSingleton<IInitializable>(sp => sp.GetRequiredService<ConsoleChatManager>());
services.AddSingleton<IUpdatable>(sp => sp.GetRequiredService<ConsoleChatManager>());
await using var serviceProvider = services.BuildServiceProvider();
// --- Execução da Aplicação ---
var logger = serviceProvider.GetRequiredService<ILogger<Program>>();
var packetRegistry = serviceProvider.GetRequiredService<IPacketRegistry>();
var gameLoop = serviceProvider.GetRequiredService<GameLoop>();
var netOptions = serviceProvider.GetRequiredService<NetworkOptions>();
logger.LogInformation($"Configurações de Rede: {netOptions.ToString()}");
// Registra manipuladores de pacotes
packetRegistry.RegisterHandler<ChatMessage>((message, context) => {
System.Console.ForegroundColor = ConsoleColor.Green;
System.Console.WriteLine($"{message.Sender}: {message.Message}");
System.Console.ResetColor();
});
// Configura o cancelamento para Ctrl+C
var cts = new CancellationTokenSource();
System.Console.CancelKeyPress += (sender, e) =>
{
logger.LogInformation("Ctrl+C pressionado. Encerrando...");
e.Cancel = true; // Impede que o processo termine abruptamente
cts.Cancel();
};
try
{
logger.LogInformation("Aplicação iniciada no modo '{Mode}'. Pressione Ctrl+C para sair.", mode);
// Executa o loop principal da aplicação
await gameLoop.RunAsync(cts.Token);
}
catch (OperationCanceledException)
{
// Esperado quando o cancelamento é solicitado.
logger.LogInformation("Loop da aplicação cancelado com sucesso.");
}
catch (Exception ex)
{
logger.LogCritical(ex, "Ocorreu um erro fatal na aplicação.");
}
finally
{
logger.LogInformation("Aplicação encerrada.");
}
}
}