Table of Contents
应用效果" >应用效果
C#获取CPU使用情况" >C#获取CPU使用情况
页面绘制处理" >页面绘制处理
服务端" >服务端
下载" >下载
Home Web Front-end H5 Tutorial HTML5-WebSocket实现对服务器CPU实时监控

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

May 17, 2016 am 09:08 AM

由于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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to run the h5 project How to run the h5 project Apr 06, 2025 pm 12:21 PM

Running the H5 project requires the following steps: installing necessary tools such as web server, Node.js, development tools, etc. Build a development environment, create project folders, initialize projects, and write code. Start the development server and run the command using the command line. Preview the project in your browser and enter the development server URL. Publish projects, optimize code, deploy projects, and set up web server configuration.

What exactly does H5 page production mean? What exactly does H5 page production mean? Apr 06, 2025 am 07:18 AM

H5 page production refers to the creation of cross-platform compatible web pages using technologies such as HTML5, CSS3 and JavaScript. Its core lies in the browser's parsing code, rendering structure, style and interactive functions. Common technologies include animation effects, responsive design, and data interaction. To avoid errors, developers should be debugged; performance optimization and best practices include image format optimization, request reduction and code specifications, etc. to improve loading speed and code quality.

How to make h5 click icon How to make h5 click icon Apr 06, 2025 pm 12:15 PM

The steps to create an H5 click icon include: preparing a square source image in the image editing software. Add interactivity in the H5 editor and set the click event. Create a hotspot that covers the entire icon. Set the action of click events, such as jumping to the page or triggering animation. Export H5 documents as HTML, CSS, and JavaScript files. Deploy the exported files to a website or other platform.

What Does H5 Refer To? Exploring the Context What Does H5 Refer To? Exploring the Context Apr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

What is the H5 programming language? What is the H5 programming language? Apr 03, 2025 am 12:16 AM

H5 is not a standalone programming language, but a collection of HTML5, CSS3 and JavaScript for building modern web applications. 1. HTML5 defines the web page structure and content, and provides new tags and APIs. 2. CSS3 controls style and layout, and introduces new features such as animation. 3. JavaScript implements dynamic interaction and enhances functions through DOM operations and asynchronous requests.

How to make pop-up windows with h5 How to make pop-up windows with h5 Apr 06, 2025 pm 12:12 PM

H5 pop-up window creation steps: 1. Determine the triggering method (click, time, exit, scroll); 2. Design content (title, text, action button); 3. Set style (size, color, font, background); 4. Implement code (HTML, CSS, JavaScript); 5. Test and deployment.

What are the advantages of H5 page production What are the advantages of H5 page production Apr 05, 2025 pm 11:48 PM

The advantages of H5 page production include: lightweight experience, fast loading speed, and improving user retention. Cross-platform compatibility, no need to adapt to different platforms, improving development efficiency. Flexibility and dynamic updates, no audit required, making it easier to modify and update content. Cost-effective, lower development costs than native apps.

Is h5 same as HTML5? Is h5 same as HTML5? Apr 08, 2025 am 12:16 AM

"h5" and "HTML5" are the same in most cases, but they may have different meanings in certain specific scenarios. 1. "HTML5" is a W3C-defined standard that contains new tags and APIs. 2. "h5" is usually the abbreviation of HTML5, but in mobile development, it may refer to a framework based on HTML5. Understanding these differences helps to use these terms accurately in your project.

See all articles