-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebMonitorService.cs
More file actions
95 lines (88 loc) · 3.25 KB
/
WebMonitorService.cs
File metadata and controls
95 lines (88 loc) · 3.25 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
using System;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace BitcoinFinder
{
public class WebMonitorService
{
private readonly HttpListener _listener = new HttpListener();
private readonly DistributedCoordinatorServer _coordinator;
private DateTime _startTime;
public WebMonitorService(DistributedCoordinatorServer coordinator, int port = 8080)
{
_coordinator = coordinator;
_listener.Prefixes.Add($"http://*:{port}/");
}
public async Task StartAsync(CancellationToken token = default)
{
_startTime = DateTime.UtcNow;
_listener.Start();
Console.WriteLine("[WEB] Listening on port 8080");
try
{
while (!token.IsCancellationRequested)
{
var context = await _listener.GetContextAsync();
_ = Task.Run(() => ProcessRequest(context));
}
}
catch (HttpListenerException)
{
// listener stopped
}
finally
{
_listener.Stop();
}
}
private async Task ProcessRequest(HttpListenerContext context)
{
var path = context.Request.Url?.AbsolutePath.ToLowerInvariant() ?? "/";
switch (path)
{
case "/":
await RespondHtml(context, "<html><body><h1>Server Status: Running</h1></body></html>");
break;
case "/api/agents":
await RespondJson(context, _coordinator.ConnectedAgents.Values);
break;
case "/api/tasks":
await RespondJson(context, _coordinator.PendingTasks.ToArray());
break;
case "/api/status":
var status = new
{
UptimeSeconds = (DateTime.UtcNow - _startTime).TotalSeconds,
Agents = _coordinator.ConnectedAgents.Count,
Tasks = _coordinator.PendingTasks.Count
};
await RespondJson(context, status);
break;
default:
context.Response.StatusCode = 404;
context.Response.Close();
break;
}
}
private static async Task RespondHtml(HttpListenerContext ctx, string html)
{
var bytes = Encoding.UTF8.GetBytes(html);
ctx.Response.ContentType = "text/html";
ctx.Response.ContentLength64 = bytes.Length;
await ctx.Response.OutputStream.WriteAsync(bytes);
ctx.Response.Close();
}
private static async Task RespondJson(HttpListenerContext ctx, object data)
{
var json = JsonSerializer.Serialize(data);
var bytes = Encoding.UTF8.GetBytes(json);
ctx.Response.ContentType = "application/json";
ctx.Response.ContentLength64 = bytes.Length;
await ctx.Response.OutputStream.WriteAsync(bytes);
ctx.Response.Close();
}
}
}