1
0
tinklu-paslaugos/Lab1/Moderator/Moderator.cs
2024-09-15 11:21:42 +03:00

117 lines
3.0 KiB
C#

using ChatRoomContract;
using Microsoft.Extensions.DependencyInjection;
using NLog;
using SimpleRpc.Transports.Http.Client;
using SimpleRpc.Serialization.Hyperion;
using SimpleRpc.Transports;
using System.Diagnostics;
using System.Security.Cryptography;
namespace Moderator;
internal class Moderator
{
private readonly List<string> FIRSTNAMES =
new List<string> {
"John", "Peter", "Jack", "Steve"
};
/// <summary>
/// A set of surnames to choose from.
/// </summary>
private readonly List<string> LASTNAMES =
new List<String> {
"Johnson", "Peterson", "Jackson", "Steveson"
};
/// <summary>
/// Logger for this class.
/// </summary>
Logger mLog = 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 rnd = new Random();
var name = FIRSTNAMES[rnd.Next(FIRSTNAMES.Count)] + " " + LASTNAMES[rnd.Next(LASTNAMES.Count)];
Console.Title = $"Moderator | ${name}";
chatRoom.SetClientName(name);
while (true)
{
}
}
private void Run()
{
//configure logging
ConfigureLogging();
//initialize random number generator
var rnd = new Random();
while (true)
{
//connect to the server, get service client proxy
var sc = new ServiceCollection();
sc
.AddSimpleRpcClient(
"chatRoomService", //must be same as on line 86
new HttpClientTransportOptions
{
Url = "http://127.0.0.1:5000/simplerpc",
Serializer = "HyperionMessageSerializer"
}
)
.AddSimpleRpcHyperionSerializer();
sc.AddSimpleRpcProxy<IChatRoomService>("chatRoomService"); //must be same as on line 77
var sp = sc.BuildServiceProvider();
var chatRoom = sp.GetService<IChatRoomService>();
Debug.Assert(chatRoom != null);
try
{
RunConnection(chatRoom);
}
catch (Exception e)
{
//log whatever exception to console
mLog.Warn(e, "Unhandled exception caught. Will restart main loop.");
//prevent console spamming
Thread.Sleep(2000);
}
}
}
static void Main(string[] args)
{
var self = new Moderator();
self.Run();
}
}