using System.Net.Sockets;
using System.Text;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Kevin;
public class App : IHostedService
{
private ILogger<App> _logger;
private string _host;
private int _port;
private Database _database;
private UdpClient _listener;
public App(
ILogger<App> logger,
Database database,
string host = "localhost",
int port = 5371)
{
_logger = logger;
_host = host;
_port = port;
_database = database;
_listener = new UdpClient(host, port);
}
public async Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation($"Listening on port {_host}:{_port}");
while (!cancellationToken.IsCancellationRequested)
{
var receiveTask = _listener.ReceiveAsync();
var cancellationTask = Task.Delay(Timeout.Infinite, cancellationToken);
var completedTask = await Task.WhenAny(receiveTask, cancellationTask);
if (completedTask == receiveTask)
{
var data = await receiveTask;
var message = Encoding.ASCII.GetString(data.Buffer);
HandleMessage(message);
}
else if (completedTask == cancellationTask)
{
break;
}
}
}
public Task StopAsync(CancellationToken cancellationToken)
{
_listener.Close();
return Task.CompletedTask;
}
private void HandleMessage(string message)
{
Console.WriteLine($"Received: {message}");
}
}