1
0
tinklu-paslaugos/Lab2-rest/Participant/Participant.cs
2024-10-17 20:31:08 +03:00

87 lines
2.2 KiB
C#

using ChatRoomContract;
using NLog;
using Bogus;
namespace Participant;
internal class Participant
{
/// <summary>
/// Logger for this class.
/// </summary>
Logger log = LogManager.GetCurrentClassLogger();
/// <summary>
/// Configures logging subsystem.
/// </summary>
private void ConfigureLogging()
{
var config = new NLog.Config.LoggingConfiguration();
var console =
new NLog.Targets.ConsoleTarget("console")
{
Layout = @"${date:format=HH\:mm\:ss}|${level}| ${message} ${exception}"
};
config.AddTarget(console);
config.AddRuleForAllLevels(console);
LogManager.Configuration = config;
}
private void RunConnection(IChatRoomService chatRoom)
{
var faker = new Faker("en");
var rnd = new Random();
var name = faker.Name.FullName();
int clientId = chatRoom.RegisterClient(name);
log.Info($"Registered with client id {clientId}");
while (true)
{
int strikes = chatRoom.GetStrikes(clientId);
Console.Title = $"Participant | {name} | {clientId} | {strikes} Strikes";
var message = string.Join(" ", faker.Lorem.Words(5));
bool needsToBeCensored = rnd.Next(0, 100) > 50;
if (chatRoom.SendMessage(clientId, message, needsToBeCensored)) {
log.Info("Sent message");
} else {
log.Info("Failed to send message, blocked");
}
Thread.Sleep(2 * 1000);
}
}
private void Run()
{
ConfigureLogging();
while (true)
{
var client = new ChatRoomClient("http://127.0.0.1:5000", new HttpClient());
try
{
RunConnection(client);
}
catch (Exception e)
{
//log whatever exception to console
log.Warn(e, "Unhandled exception caught. Will restart main loop.");
//prevent console spamming
Thread.Sleep(2000);
}
}
}
static void Main(string[] args)
{
var self = new Participant();
self.Run();
}
}