search
HomeWeb Front-endH5 TutorialHTML5-WebSocket实现对服务器CPU实时监控

由于WebSocket允许保持长连接,因此当建立连接后服务器可以主动地向Client发送相关信息.下面通过服务端获取当前CPU的使用情况主动发送给网页,让网页实时显示CPU使用情况的曲线图.该事例的主要功能是包括服务端获取CPU使和情况和HTML5使用canvas进行曲线图绘制.


应用效果


HTML5-WebSocket实现对服务器CPU实时监控


实现效果主要是模仿windows的任务管理器,显示每个核的工作情况.


C#获取CPU使用情况


可能通过PerformanceCounter来获取具本CPU线程的使用情况,不过在构建PerformanceCounter前先获取到CPU对应的线程数量.获取这个数量可以通过Environment.ProcessorCount属性获取,然后遍历构建每个PerformanceCounter


1
2
3
4
5
int coreCount = Environment.ProcessorCount;        
            for (int i = 0; i
            {
                mCounters.Add(new PerformanceCounter("Processor", "% Processor Time", i.ToString()));
            }


为了方便计数器的处理,简单地封装了一个基础类,完整代码如下:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/// <summary> </summary>
    /// Copyright © henryfan 2012        
    ///Email:   henryfan@msn.com    
    ///HomePage:    <a href="http://www.ikende.com%20%20%20%20%20%20%20/">http://www.ikende.com       </a>
    ///CreateTime:  2012/12/24 15:10:44
    ///
    public class ProcessorCounter
    {
        private List<performancecounter> mCounters = </performancecounter>new List<performancecounter>(); </performancecounter>
        public IList<performancecounter> Counters </performancecounter>
        {
            get
            {
                return mCounters;
            }
        }
        public void Open()
        {
            int coreCount = Environment.ProcessorCount;        
            for (int i = 0; i
            {
                mCounters.Add(new PerformanceCounter("Processor", "% Processor Time", i.ToString()));
            }
        }
        public ItemUsage[] GetValues()
        {
            ItemUsage[] values = new ItemUsage[mCounters.Count];
            for (int i = 0; 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; }
    }


这样一个用于统计CPU所有线程使用情况计数的类就完成了.


页面绘制处理


首先定义一些简单的处理结构


1
2
3
4
5
6
7
8
9
10
11
function ProcessorInfo() {
            this.Item = null;
            this.Points = new Array();
            for (var i = 0; i
                this.Points.push(new Point(0, 0));
            }
        }
        function Point(x, y) {
            this.X = x;
            this.Y = y;
        }


主要定义线程信息结构,默认初始化50个座标,当在接收服务线程使用情况的时候,构建一个点添加到数组件尾部同时把第一个移走.通过定时绘制这50个点的曲线这样一个动态的走势就可以完成了.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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
  
                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' '" width="200" height="110">').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));
            }
        }


只需要通过定时器来不停地更新线程使用绘制即可.


1
2
3
4
5
setInterval(function () {
                for (var i = 0; i
                    drawProceessor(processors[i]);
                }
            }, 1000);


服务端


对于服务端其实可以根据自己的需要来使用websocket协议实现,.net 4.5也提供相应的封装.而这里则使用了beetle对应websocket的扩展协议包,整体代码如下:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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);
            
        }
    }

每秒获取一次CPU的使用情况,并把信息以json的方式发送给当前所有在线的连接.

下载

完整代码:ProcessorsMonitor.rar (686.02 kb) 

演示地址:http://html5.ikende.com/ProcessorsMonitor.htm (浏览器使用chrome或IE10)


via:http://www.cnblogs.com/smark/archive/2012/12/25/2833129.html



Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
H5: New Features and Capabilities for Web DevelopmentH5: New Features and Capabilities for Web DevelopmentApr 29, 2025 am 12:07 AM

H5 brings a number of new functions and capabilities, greatly improving the interactivity and development efficiency of web pages. 1. Semantic tags such as enhance SEO. 2. Multimedia support simplifies audio and video playback through and tags. 3. Canvas drawing provides dynamic graphics drawing tools. 4. Local storage simplifies data storage through localStorage and sessionStorage. 5. The geolocation API facilitates the development of location-based services.

H5: Key Improvements in HTML5H5: Key Improvements in HTML5Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

HTML5: The Standard and its Impact on Web DevelopmentHTML5: The Standard and its Impact on Web DevelopmentApr 27, 2025 am 12:12 AM

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 Code Examples: Practical Applications and TutorialsH5 Code Examples: Practical Applications and TutorialsApr 25, 2025 am 12:10 AM

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

The Connection Between H5 and HTML5: Similarities and DifferencesThe Connection Between H5 and HTML5: Similarities and DifferencesApr 24, 2025 am 12:01 AM

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

The Building Blocks of H5 Code: Key Elements and Their PurposeThe Building Blocks of H5 Code: Key Elements and Their PurposeApr 23, 2025 am 12:09 AM

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

HTML5 and H5: Understanding the Common UsageHTML5 and H5: Understanding the Common UsageApr 22, 2025 am 12:01 AM

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5: The Building Blocks of the Modern Web (H5)HTML5: The Building Blocks of the Modern Web (H5)Apr 21, 2025 am 12:05 AM

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools