-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
89 lines (75 loc) · 2.45 KB
/
Program.cs
File metadata and controls
89 lines (75 loc) · 2.45 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
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using EngineIO.Client;
using Microsoft.Extensions.Logging;
#if DEBUG
using Microsoft.Extensions.Logging.Console;
#else
using Microsoft.Extensions.Logging.Abstractions;
#endif
namespace PingPong;
internal class Program : IDisposable
{
private readonly ILoggerFactory loggerFactory;
private readonly ILogger<Program> logger;
private static readonly CancellationTokenSource cts = new();
Program()
{
#if DEBUG
var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddSimpleConsole(o =>
{
o.TimestampFormat = "[yyyy-MM-dd HH:mm:ss] ";
o.SingleLine = true;
o.ColorBehavior = LoggerColorBehavior.Enabled;
}).SetMinimumLevel(LogLevel.Debug);
});
logger = loggerFactory.CreateLogger<Program>();
#else
this.loggerFactory = NullLoggerFactory.Instance;
this.logger = loggerFactory.CreateLogger<Program>();
#endif
Engine = new Engine((options) =>
{
options.BaseAddress = "http://127.0.0.1:9854";
options.AutoUpgrade = true;
}, loggerFactory);
}
public Engine Engine { get; }
private static async Task Main(string[] args)
{
Console.CancelKeyPress += async (sender, eventArgs) =>
{
await cts.CancelAsync();
};
var program = new Program();
program.logger.LogDebug("Client Starting...");
await program.Engine.ConnectAsync(cts.Token);
await Task.WhenAll(Task.Run(program.EmitAsync, cts.Token), Task.Run(program.ListenAsync, cts.Token));
program.logger.LogDebug("Disconnecting...");
await program.Engine.DisconnectAsync();
}
private async Task ListenAsync()
{
await foreach (var packet in Engine.ListenAsync(cts.Token))
{
var message = Encoding.UTF8.GetString(packet.Body.Span);
logger.LogInformation("Server: {message}", message);
}
}
private async Task EmitAsync()
{
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(2));
while (await timer.WaitForNextTickAsync(cts.Token))
{
await Engine.SendAsync("Ping", cts.Token);
}
}
public void Dispose()
{
Engine.Dispose();
}
}