C# 监控网速
主要有两个类,其一是NetworkAdapter,该类的作用是获取本机网络适配器列表,并且可以通过该类的属性获取当前网速数据;其二是NetworkMonitor,该类是通过.NET的PerformanceCounter(性能计数器组件)监测本机每一个网络适配器对应的当前网速状况(翻译得不大好,具体还是看原汁原味的代码吧:))
NetworkAdapter类
using System;
using System.Diagnostics; namespace NetWorkSpeedMonitor
{
/// <summary>
/// Represents a network adapter installed on the machine.
/// Properties of this class can be used to obtain current network speed.
/// </summary>
public class NetworkAdapter
{
/// <summary>
/// Instances of this class are supposed to be created only in an NetworkMonitor.
/// </summary>
internal NetworkAdapter(string name)
{
this.name = name;
} private long dlSpeed, ulSpeed; // Download/Upload speed in bytes per second.
private long dlValue, ulValue; // Download/Upload counter value in bytes.
private long dlValueOld, ulValueOld; // Download/Upload counter value one second earlier, in bytes. internal string name; // The name of the adapter.
internal PerformanceCounter dlCounter, ulCounter; // Performance counters to monitor download and upload speed.
/// <summary>
/// Preparations for monitoring.
/// </summary>
internal void init()
{
// Since dlValueOld and ulValueOld are used in method refresh() to calculate network speed, they must have be initialized.
this.dlValueOld = this.dlCounter.NextSample().RawValue;
this.ulValueOld = this.ulCounter.NextSample().RawValue;
}
/// <summary>
/// Obtain new sample from performance counters, and refresh the values saved in dlSpeed, ulSpeed, etc.
/// This method is supposed to be called only in NetworkMonitor, one time every second.
/// </summary>
internal void refresh()
{
this.dlValue = this.dlCounter.NextSample().RawValue;
this.ulValue = this.ulCounter.NextSample().RawValue; // Calculates download and upload speed.
this.dlSpeed = this.dlValue - this.dlValueOld;
this.ulSpeed = this.ulValue - this.ulValueOld; this.dlValueOld = this.dlValue;
this.ulValueOld = this.ulValue;
}
/// <summary>
/// Overrides method to return the name of the adapter.
/// </summary>
/// <returns>The name of the adapter.</returns>
public override string ToString()
{
return this.name;
}
/// <summary>
/// The name of the network adapter.
/// </summary>
public string Name
{
get { return this.name; }
}
/// <summary>
/// Current download speed in bytes per second.
/// </summary>
public long DownloadSpeed
{
get { return this.dlSpeed; }
}
/// <summary>
/// Current upload speed in bytes per second.
/// </summary>
public long UploadSpeed
{
get { return this.ulSpeed; }
}
/// <summary>
/// Current download speed in kbytes per second.
/// </summary>
public double DownloadSpeedKbps
{
get { return this.dlSpeed / 1024.0; }
}
/// <summary>
/// Current upload speed in kbytes per second.
/// </summary>
public double UploadSpeedKbps
{
get { return this.ulSpeed / 1024.0; }
}
}
}
NetworkMonitor类
using System;
using System.Timers;
using System.Collections;
using System.Diagnostics; namespace NetWorkSpeedMonitor
{
/// <summary>
/// The NetworkMonitor class monitors network speed for each network adapter on the computer,
/// using classes for Performance counter in .NET library.
/// </summary>
public class NetworkMonitor
{
private Timer timer; // The timer event executes every second to refresh the values in adapters.
private ArrayList adapters; // The list of adapters on the computer.
private ArrayList monitoredAdapters;// The list of currently monitored adapters. public NetworkMonitor()
{
this.adapters = new ArrayList();
this.monitoredAdapters = new ArrayList();
EnumerateNetworkAdapters(); timer = new Timer();
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
}
/// <summary>
/// Enumerates network adapters installed on the computer.
/// </summary>
private void EnumerateNetworkAdapters()
{
PerformanceCounterCategory category = new PerformanceCounterCategory("Network Interface"); foreach (string name in category.GetInstanceNames())
{
// This one exists on every computer.
if (name == "MS TCP Loopback interface")
continue;
// Create an instance of NetworkAdapter class, and create performance counters for it.
NetworkAdapter adapter = new NetworkAdapter(name);
adapter.dlCounter = new PerformanceCounter("Network Interface", "Bytes Received/sec", name);
adapter.ulCounter = new PerformanceCounter("Network Interface", "Bytes Sent/sec", name);
this.adapters.Add(adapter); // Add it to ArrayList adapter
}
} private void timer_Elapsed(object sender, ElapsedEventArgs e)
{
foreach (NetworkAdapter adapter in this.monitoredAdapters)
adapter.refresh();
}
/// <summary>
/// Get instances of NetworkAdapter for installed adapters on this computer.
/// </summary>
public NetworkAdapter[] Adapters
{
get { return (NetworkAdapter[])this.adapters.ToArray(typeof(NetworkAdapter)); }
}
/// <summary>
/// Enable the timer and add all adapters to the monitoredAdapters list,
/// unless the adapters list is empty.
/// </summary>
public void StartMonitoring()
{
if (this.adapters.Count > )
{
foreach (NetworkAdapter adapter in this.adapters)
if (!this.monitoredAdapters.Contains(adapter))
{
this.monitoredAdapters.Add(adapter);
adapter.init();
} timer.Enabled = true;
}
}
/// <summary>
/// Enable the timer, and add the specified adapter to the monitoredAdapters list
/// </summary>
public void StartMonitoring(NetworkAdapter adapter)
{
if (!this.monitoredAdapters.Contains(adapter))
{
this.monitoredAdapters.Add(adapter);
adapter.init();
}
timer.Enabled = true;
}
/// <summary>
/// Disable the timer, and clear the monitoredAdapters list.
/// </summary>
public void StopMonitoring()
{
this.monitoredAdapters.Clear();
timer.Enabled = false;
}
/// <summary>
/// Remove the specified adapter from the monitoredAdapters list, and
/// disable the timer if the monitoredAdapters list is empty.
/// </summary>
public void StopMonitoring(NetworkAdapter adapter)
{
if (this.monitoredAdapters.Contains(adapter))
this.monitoredAdapters.Remove(adapter);
if (this.monitoredAdapters.Count == )
timer.Enabled = false;
}
}
}
Form关键代码
using NetWorkSpeedMonitor; private NetworkAdapter[] adapters;
private NetworkMonitor monitor; private void FormMain_Load(object sender, System.EventArgs e)
{
monitor = new NetworkMonitor();
this.adapters = monitor.Adapters;
/* If the length of adapters is zero, then no instance
* exists in the networking category of performance console.*/
if (adapters.Length == )
{
this.ListAdapters.Enabled = false;
MessageBox.Show("No network adapters found on this computer.");
return;
}
this.ListAdapters.Items.AddRange(this.adapters);
} private void ListAdapters_SelectedIndexChanged(object sender, System.EventArgs e)
{
monitor.StopMonitoring();
// Start a timer to obtain new performance counter sample every second.
monitor.StartMonitoring(adapters[this.ListAdapters.SelectedIndex]);
this.TimerCounter.Start();
} private void TimerCounter_Tick(object sender, System.EventArgs e)
{
NetworkAdapter adapter = this.adapters[this.ListAdapters.SelectedIndex];
/* The DownloadSpeedKbps and UploadSpeedKbps are double values. You can also
* use properties DownloadSpeed and UploadSpeed, which are long values but
* are measured in bytes per second. */
this.LableDownloadValue.Text = String.Format("{0:n} kbps", adapter.DownloadSpeedKbps);
this.LabelUploadValue.Text = String.Format("{0:n} kbps", adapter.UploadSpeedKbps);
}
C# 监控网速的更多相关文章
- iOS开发——实时监控网速(仅作参考,发现一点问题)
开发中用到获取网速的地方,应该就两种: 1.下载速度,这种可以直接在接受数据的地方统计计算.这个就不讲了. 2.获取手机网卡的数据,可以监控网卡的进出流量,下面就是. #import "Vi ...
- linux 实时监控网速脚本(转)
#!/bin/bash ethn=$ while true do RX_pre=$(cat /proc/net/dev | grep $ethn | sed 's/:/ /g' | awk '{pri ...
- iOS 直播-网速监控
iOS 直播-网速监控 CXNetworkSpeed.h // // CXNetworkSpeed.h // CXNetworkSpeedDemo // // Created by xubaoaich ...
- Nload(CentOS网速的实时监控)
Nload(CentOS网速的实时监控)的安装和安装过程中的问题 I. 安装 Download the latest rpmforge-release rpm from wget ftp://ftp. ...
- linux网络监控_网速测试
Linux下查看网络即时网速 1.sar命令(一般般) sar -n DEV 1 100 1代表一秒统计并显示一次 100代表统计一百次 sar在sysstat包 2.使用ntop图形工具(没详细用过 ...
- 网速监控-nload
用来监控系统网卡实时网速的. 安装 yum install nload -y # 或 apt install nload -y 使用 # 直接运行默认监控第一个网卡, 使用上下方向键来切换网卡. nl ...
- shell小脚本--网速监控
在windows中,我们可以在360等管家软件中显示网速,在linux下想要查看实时的网速怎么办呢?当然在linux下也有很多优秀的软件可以实时显示网络状况!但是在这里我们使用shell脚本来先完成网 ...
- 【树莓派】Linux 测网速及树莓派源
这篇文章比较杂,其中包含三点:linux环境中测试网络速度,树莓派下载软件的源,部分我写好的脚本: 一.Linux 测网速 Linux 测网速: sar -n DEV 1 100 1代表一秒统计并显示 ...
- 媲美5G的Wifi网速、“备战”资产一键领……揭秘双11小二背后的保障力量
如今,双11不光是购物狂欢节,更是对技术的一次“大考”,对于阿里巴巴企业内部运营的基础保障技术而言,亦是如此. 回溯双11历史,这背后也经历过“小米加步枪”的阶段:作战室从随处是网线,交换机放地上的“ ...
随机推荐
- Django框架(十二)-- 中间件、CSRF跨站请求伪造
中间件 一.什么是中间件 请求的时候需要先经过中间件才能到达django后端(urls,views,templates,models) 响应的时候也需要经过中间件才能到达web服务网关接口 djang ...
- Bash速查表
例 #!/usr/bin/env bash NAME="John" echo "Hello $NAME!" 变量 NAME="John" e ...
- highcharts离线导出图表
到了这里,其实还没有结束,导出图片时,仍会发出两个请求 此时找到offline-exporting.js文件修改其中的libURL 修改为请求自己的网站
- .Net Core SignalR+LayUi(1)-简单入门
本系列主要开发客服聊天系统的总结. 基于.Net Core2.2 +SignalR+Layui实现的人对人聊天功能 SignalR简介 SignalR是一个.Net Core/.Net Framewo ...
- angular复习笔记4-模板
Angular复习笔记4-模板 简介 模板是一种自定义的标准化页面,通过模板和模板中的数据结合,可以生成各种各样的网页.在Angular中,模板的默认语言是HTML,几乎所有的HTML语法在模板中都是 ...
- C语言-MySQL单表查询(vs2013环境)
一.首先配置项目属性: 1.打开mysql的安装路径,找到include文件夹和lib文件夹 如图: 2.在vs2013中, 打开项目–> 属性 –>VC++目录 如图: 把将nclude ...
- DNS原理及劫持问题
对于互联网,人们总是高谈阔论,却很少有人愿意去了解电脑.手机.电视这些设备到底是如何被“连接”起来的.本文通过“我”,一个普通的网络请求的视角,给大家介绍下“我”的工作流程是如何的. 人们动动手指,点 ...
- OO第三单元作业总结
OO第三单元作业总结--JML 第三单元的主题是JML规格的学习,其中的三次作业也是围绕JML规格的实现所展开的(虽然感觉作业中最难的还是如何正确适用数据结构以及如何正确地对于时间复杂度进行优化). ...
- VUE过滤器 基础回顾5
过滤器是一种在模板中处理数据的便捷方式,特别适合对字符串和数组进行简易显示 <div id="app"> <p>商品1花费{{oneCost | froma ...
- Gitlab配置webhooks实现自动化部署
Gitlab 自动化部署 原理介绍 配置gitlab当push动作的时候,访问服务器上的一个链接比如www.shenke.group/hook.php hook.php里面写着一行代码,会让服务器gi ...