下面的代码是我用来 ping 8.8.8.8 的代码,但有时当我按下开始时,它只是丢包,这很重要,这很奇怪,因为我确定我没有那么多丢包,然后我暂停它并重新开始,它工作得很好,这对我来说没有意义,我很茫然。
我添加了 Thread.Sleep(); 因为我猜我启动它时程序可能没有加载,但这也很奇怪!这是一个如此小而简单的程序,它不应该有这样的问题
我还有一个问题,我应该为此设置什么超时时间,现在应用程序每秒发送一个数据包,每 900 毫秒丢弃一次,我应该把它设置为高于 900 还是会降低性能?
public partial class Form1 : Form
{
public int PingTime;
public int pingor = 0;
public int pingur = 0;
public int maxping;
public int minping;
public Int64 avgping;
public string avrage;
public int ping_no;
public string fail;
public string msg1 = " Packet Lost ";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (timer1.Enabled == true )
{
timer1.Enabled = false;
Thread.Sleep(1000);
}
else if (timer1.Enabled == false)
{
timer1.Enabled = true;
Thread.Sleep(1000);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
bool pingable = false;
PingOptions options = new PingOptions();
options.DontFragment = true;
string data = "1";
byte[] buffer = Encoding.ASCII.GetBytes(data);
Ping pinger = new Ping();
try
{
//37.58.117.146
//8.8.8.8
PingReply reply = pinger.Send("8.8.8.8", 900, buffer, options);
pingable = reply.Status == IPStatus.Success;
string pingtime = reply.RoundtripTime.ToString();
int newpingtime = Convert.ToInt32(pingtime);
if (reply.Status == IPStatus.Success)
{
label1.Text = reply.RoundtripTime.ToString();
}
else
{
label1.Text = msg1;
}
//_________________________Max Ping
if (maxping == 0)
{
maxping = Convert.ToInt32(newpingtime);
}
else if (newpingtime >= Convert.ToInt32(maxping))
{
maxping = Convert.ToInt32(newpingtime);
}
lblmax.Text = maxping.ToString();
//_________________________Min Ping
if (reply.Status == IPStatus.Success && minping == 0 && newpingtime == 0)
{
lblmin.Text = minping.ToString();
}
else if (reply.Status == IPStatus.Success && lblmin.Text == " - - -" && newpingtime >= 0)
{
minping = newpingtime;
lblmin.Text = minping.ToString();
}
else if (reply.Status == IPStatus.Success && newpingtime < minping)
{
minping = newpingtime;
lblmin.Text = minping.ToString();
}
//_________________________Ping AVG
if (reply.Status == IPStatus.Success)
{
avgping = avgping + newpingtime;
ping_no = ping_no + 1;
lblavg.Text = Convert.ToString(avgping / ping_no);
}
}
catch (PingException error)
{
MessageBox.Show(error.Message);
}
if (pingable == true)
{
pingor++;
}
if (pingable == false)
{
pingur++;
}
lblrecived.Text = Convert.ToString(pingor);
lbllost.Text = Convert.ToString(pingur);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Thread.Sleep(900);
}
在此先感谢,只是让您知道我的丢包率不超过 2%,这不应该显示 40 个丢包和 0 个收到!而且它在 80% 的时间里都能正常工作!
当我暂停并再次快速启动它或第一次启动它时会再次发生这种情况。