Isso é muito simples ! Cada componente tem um objeto NetworkInterface estatísticas de interface que fornece dados estatísticos para uma interface de rede no computador local. Depende que Internet Protocol seu uso (IPv4 ou IPv6 ), você pode facilmente pegar essa informação ! Para fazer isso em C # que faça o seguinte:
CODE:. IPv4InterfaceStatistics interfaceStats = NetworkInterface.GetAllNetworkInterfaces ( ) [ 0 ] GetIPv4Statistics ( ) ;
A partir desse objeto , podemos buscar o BytesSent e BytesReceived de que a interface de rede. Através da criação de um temporizador simples que manipula cada taxa de carraça em cada intervalo de 1 seg , podemos encontrar a velocidade de bytes por segundo por encontrar a diferença entre os novos bytes com respeito aos anteriores . Para torná-lo mais legível , poderíamos converter bytes em kilobytes , dividindo por 1024 .
CODE:/ / Globalmente declarar estes últimosint bytesSentSpeed = 0 ;int bytesReceivedSpeed = 0 ;
/ / Velocidade Grab em KB / sbytesSentSpeed = (int ) ( interfaceStats.BytesSent - bytesSentSpeed ) / 1024;bytesReceivedSpeed = (int ) ( interfaceStats.BytesReceived - bytesReceivedSpeed ) / 1024;
Isso é que é ! Isso é como você fazer o seu próprio medidor de largura de banda em . NET . Dê uma olhada no meu post anterior sobre como criar um ambiente mais sofisticado temporizador do Windows que depende do kernel CPU carrapato tempo em vez de. Net. Exige interoping Kernel32.dll , mas você vai ter estatísticas mais precisas do que usando o Windows.Forms.Timer . A diferença é muito significativa . Windows.Forms.Timer funciona a resolução de 1 segundo , enquanto a resolução Kernel é de 10 milissegundos ! Essa é uma grande diferença e fará com que seus resultados mais exato!código final
CODE:using System;usando System.Net.NetworkInformation ;using System.Windows.Forms;
namespace InterfaceTrafficWatch{
/ / /
/ / / Por Mohamed Mansour
/ / /
/ / / Livre para usar sob a GPL licença open source!
/ / / </ Summary>
MainForm público classe parcial : Form
{
/ / /
/ / / </ Summary>
private const timerUpdate duplo = 1000;
/ / /
/ / / </ Summary>
NetworkInterface privado [] nicArr ;
/ / /
/ / / ( Que poderia usar algo mais eficiente como
/ / / Como chamadas de interoperabilidade para HighPerformanceTimers )
/ / / </ Summary>
private Timer timer ;
/ / /
/ / / </ Summary>
MainForm pública ()
{
InitializeComponent ( ) ;
InitializeNetworkInterface ( ) ;
InitializeTimer ( ) ;
}
/ / /
/ / / </ Summary>
InitializeNetworkInterface private void ()
{
/ / Pegue todas as interfaces locais para este computador
nicArr NetworkInterface.GetAllNetworkInterfaces = ( ) ;
/ / Adiciona o nome de cada interface para caixa de combinação
for (int i = 0; i < nicArr.Length ; i + +)
cmbInterface.Items.Add ( . nicArr [i ] Nome );
/ / Muda a seleção inicial para a primeira interface
cmbInterface.SelectedIndex = 0 ;
}
/ / /
/ / / </ Summary>
private void InitializeTimer ()
{
timer = new Timer ();
Timer.Interval = (int) timerUpdate ;
Timer.Tick + = new EventHandler ( timer_Tick );
timer.Start ( ) ;
}
/ / /
/ / / </ Summary>
UpdateNetworkInterface private void ()
{
/ / Object Grab NetworkInterface que descreve a interface atual
NetworkInterface nic = nicArr [ cmbInterface.SelectedIndex ];
/ / Pega as estatísticas de que a interface
IPv4InterfaceStatistics interfaceStats nic.GetIPv4Statistics = ( ) ;
/ / Calcular a velocidade de bytes que entram e saem
/ / NOTA: nós poderíamos usar algo mais rápido e mais confiável do que o Windows Forms Tiemr
/ / Tal como HighPerformanceTimer http://www.m0interactive.com/archives/2006/12/21/high_resolution_timer_in_net_2_0.html
int bytesSentSpeed = (int ) ( interfaceStats.BytesSent - Double.Parse ( lblBytesSent.Text )) / 1024;
int bytesReceivedSpeed = (int ) ( interfaceStats.BytesReceived - Double.Parse ( lblBytesReceived.Text )) / 1024;
/ / Atualiza os rótulos
lblSpeed.Text nic.Speed.ToString = ( ) ;
lblInterfaceType.Text nic.NetworkInterfaceType.ToString = ( ) ;
lblSpeed.Text nic.Speed.ToString = ( ) ;
lblBytesReceived.Text interfaceStats.BytesReceived.ToString = ( ) ;
lblBytesSent.Text interfaceStats.BytesSent.ToString = ( ) ;
lblUpload.Text = bytesSentSpeed.ToString ( ) + " KB / s";
lblDownload.Text = bytesReceivedSpeed.ToString ( ) + " KB / s";
}
/ / /
/ / / </ Summary>
/ / / </ param>
/ / / </ param>
vazio timer_Tick (object sender, EventArgs e)
{
UpdateNetworkInterface ( ) ;
}
}}
Baixe aqui : http://www.m0interactive.com/download/10.00
0 comentários:
Postar um comentário