// (c) 2007 Richard Grimes // www.grimes.demon.co.uk using System; using System.Diagnostics; class Server { const string catName = "Data Generator"; const string catHelp = "Generates random sample data"; const string ctrName = "# Connected Clients"; const string ctrHelp = "The number of clients connected to the server"; const string ctrRateName = "# of clients connecting per sec"; const string ctrRateHelp = "The rate that clients connect"; static PerformanceCounter clients; static PerformanceCounter totalClients; static void Main(string[] args) { if (args.Length > 0) { // Delete category if (PerformanceCounterCategory.Exists(catName)) { PerformanceCounterCategory.Delete(catName); } return; } if (!PerformanceCounterCategory.Exists(catName)) { // Create new counter if it does not exist CounterCreationDataCollection ccdc = new CounterCreationDataCollection(); CounterCreationData ccd = new CounterCreationData(ctrName, ctrHelp, PerformanceCounterType.NumberOfItems32); ccdc.Add(ccd); ccd = new CounterCreationData(ctrRateName, ctrRateHelp, PerformanceCounterType.RateOfCountsPerSecond32); ccdc.Add(ccd); PerformanceCounterCategory.Create( catName, catHelp, PerformanceCounterCategoryType.SingleInstance, ccdc); Console.WriteLine("Category created, re-run the application"); return; } Console.CancelKeyPress += CtrlCHandler; // Provide counters clients = new PerformanceCounter(catName, ctrName, false); totalClients = new PerformanceCounter(catName, ctrRateName, false); Random rand = new Random(Environment.TickCount); int numberOfClients = 5; totalClients.RawValue = numberOfClients; Console.WriteLine("Press Ctrl-C to end the server"); while (true) { // Simulate clients attaching and detaching int val = rand.Next(100); if (val > 66) { numberOfClients++; totalClients.Increment(); } if (val < 33) numberOfClients--; if (numberOfClients < 0) numberOfClients = 0; clients.RawValue = numberOfClients; System.Threading.Thread.Sleep(100); } } static void CtrlCHandler(object o, ConsoleCancelEventArgs a) { if (clients != null) clients.Close(); if (totalClients != null) totalClients.Close(); Console.WriteLine("Finished"); } }