Because WebSocket allows persistent connections, the server can actively send related information to the Client after the connection is established. the following shows how the current CPU usage is obtained on the server and sent to the webpage to display the CPU usage curve in real time. the main function of this example is to obtain the CPU usage and situation from the server and draw a graph using canvas in HTML5. the application effect is achieved by imitating the windows Task Manager and displaying the working status of each core. C # obtain CPU usage
The CPU thread usage may be obtained through PerformanceCounter, but the number of threads corresponding to the CPU is obtained before the PerformanceCounter is constructed. you can use Environment to obtain this quantity. obtain the ProcessorCount attribute, and traverse and construct each PerformanceCounter int coreCount = Environment. processorCount; for (int I = 0; I <coreCount; I ++) {mCounters. add (new PerformanceCounter ("Processor", "% Processor Time", I. toString ();} to facilitate counter processing, a basic class is encapsulated. The complete code is as follows: // <summary> // Copyright©Henryfan 2012 // Email: henryfan@msn.com // HomePage: http://www.ikende.com /// CreateTime: 15:10:44 /// </summary> public class ProcessorCounter {private List <PerformanceCounter> mCounters = new List <PerformanceCounter> (); public IList <PerformanceCounter> Counters {get {return mCounters ;}} public void Open () {int coreCount = Environment. processorCount; for (int I = 0; I <coreCount; I ++) {mCounters. add (new PerformanceCounter ("Processor", "% Processor Time", I. toString ();} public ItemUsage [] GetValues () {ItemUsage [] values = new ItemUsage [mCounters. count]; for (int I = 0; I <mCounters. count; I ++) {values [I] = new ItemUsage (); values [I]. ID = I. toString (); values [I]. name = "CPU" + I. toString (); values [I]. percent = mCounters [I]. nextValue () ;}return values ;}} public class ItemUsage {public string Name {get; set;} public float Percent {get; set;} public string ID {get; set ;}} this class is used to count the usage of all CPU threads. page rendering processing first defines some simple processing structure function ProcessorInfo () {this. item = null; this. points = new Array (); for (var I = 0; I <50; I ++) {this. points. push (new Point (0, 0) ;}} function Point (x, y) {this. X = x; this. Y = y;} mainly defines the thread information structure. By default, 50 coordinates are initialized. When receiving service thread usage, add a point to the end of the data component and remove the first vertex. by regularly drawing the curves of these 50 points, such a dynamic trend can be completed. function drawProceessor (item) {var canvas = document. getElementById ('processimg '+ item. item. ID); var context = canvas. getContext ('2d '); context. beginPath (); context. rect (0, 0,200,110); context. fillStyle = 'black'; context. fill (); context. lineWidth = 2; context. strokeStyle = 'white'; context. stroke (); context. beginPath (); context. moveTo (2,106); for (var I = 0; I <item. points. length; I ++) {context. lineTo (4 * I + 2,110-item. points [I]. y-4);} context. lineTo (200,106); context. closePath (); context. lineWidth = 1; context. fillStyle = '# 7fff00'; context. fill (); context. strokeStyle = '#7CFC00'; context. stroke (); context. font = '12pt Calibri '; context. fillStyle = 'white'; context. fillText (item. item. name, 60, 20);} function addUploadItem (info) {if (cpus [info. ID] = null) {var pinfo = new ProcessorInfo (); pinfo. item = info; $ ('<canvas id = "processimg' + info. ID + '"width =" 200 "height =" 110 "> </canvas> '). appendTo ($ ('# lstProcessors'); cpus [info. ID] = pinfo; processors. push (pinfo); pinfo. points. shift (); pinfo. points. push (new Point (0, info. percent); drawProceessor (pinfo);} else {var pinfo = cpus [info. ID]; pinfo. points. shift (); pinfo. points. push (new Point (0, info. percent) ;}} you only need to use the timer to continuously update the thread and use the painting. setInterval (function () {for (var I = 0; I <processors. length; I ++) {drawProceessor (processors [I]) ;}}, 1000); the server can actually use the websocket protocol for the server based on its own needs ,. net 4.5 also provides the corresponding encapsulation. here, the extended protocol package corresponding to the beetle websocket is used. The overall code is as follows: class Program: WebSocketJsonServer {static void Main (string [] args) {TcpUtils. setup ("beetle"); Program server = new Program (); server. open( 8070); Console. writeLine ("websocket start @ 8070"); ProcessorCounter counters = new ProcessorCounter (); counters. open (); while (true) {ItemUsage [] items = counters. getValues (); foreach (ItemUsage item in items) {Console. writeLine ("{0 }:{ 1} %", item. name, item. percent);} JsonMessage message = new JsonMessage (); message. type = "cpu useage"; message. data = items; foreach (TcpChannel channel in server. server. getOnlines () {channel. send (message);} System. threading. thread. sleep (995);} System. threading. thread. sleep (-1);} protected override void OnError (object sender, ChannelErrorEventArgs e) {base. onError (sender, e); Console. writeLine (e. exception. message);} protected override void OnConnected (object sender, ChannelEventArgs e) {base. onConnected (sender, e); Console. writeLine ("{0} connected", e. channel. endPoint);} protected override void OnDisposed (object sender, ChannelDisposedEventArgs e) {base. onDisposed (sender, e); Console. writeLine ("{0} disposed", e. channel. endPoint) ;}} obtains the CPU usage every second and sends the information to all online connections in json format.