using ChatRoomContract; using Microsoft.Extensions.DependencyInjection; using NLog; using SimpleRpc.Transports.Http.Client; using SimpleRpc.Serialization.Hyperion; using SimpleRpc.Transports; using System.Diagnostics; using Bogus; namespace Participant; internal class Participant { /// /// Logger for this class. /// Logger log = LogManager.GetCurrentClassLogger(); /// /// Configures logging subsystem. /// 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() { //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("chatRoomService"); //must be same as on line 77 var sp = sc.BuildServiceProvider(); var chatRoom = sp.GetService(); Debug.Assert(chatRoom != null); try { RunConnection(chatRoom); } 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(); } }