您的位置:首页 > 编程语言 > C#

C# 判断设备是否在线

2016-07-05 15:30 232 查看
1 ping类

using System;
using System.Collections.Generic;
using System.Text;
using System.Net.NetworkInformation;
using System.Threading;
using System.Windows.Forms;

namespace TestLoadForm
{
class PingIp
{
Thread thread;
int ping_time = 2000;
System.Timers.Timer timer;
public string Ip;
public delegate void PingHandle(string ip,bool flag);
public event PingHandle pingEvent;

public PingIp(string ip)
{
Ip = ip;
thread = new Thread(new ThreadStart(RunSecondThread));
thread.Start();
}

void RunSecondThread()
{
timer = new System.Timers.Timer(ping_time);
timer.AutoReset = true;
timer.Enabled = true;
timer.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);
}

void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (PingStop == false)
{
AutoPingIP(Ip);
}
else
{
timer.Stop();
}
}

bool PingStop = false;

void AutoPingIP(string ip)
{
Ping p = new Ping();
PingOptions ops = new PingOptions();
ops.DontFragment = true;
string d = "test data";
byte[] buf = Encoding.ASCII.GetBytes(d);
int timeout = 3000;

PingReply pr = p.Send(ip, timeout, buf, ops);
if(ip != "")
{
if (pr.Status == IPStatus.Success)
{
if (pingEvent != null)
pingEvent(ip,true);
}
else
{
if (pingEvent != null )
{
PingStop = true;
pingEvent(ip,false);
}
}
}
}

public void StopTh()
{
if (timer != null)
{
timer.Dispose();
}
if (thread != null)
{
if (thread.IsAlive)
thread.Abort();
}
}
}
}


2 测试

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

PingIp ping;
private void Form1_Load(object sender, EventArgs e)
{
ping = new PingIp("192.168.100.204");
ping.pingEvent += new PingIp.PingHandle(ping_pingEvent);
}

void ping_pingEvent(string ip, bool flag)
{
this.Invoke(new MethodInvoker(delegate()
{
textBox1.Text += "ip:"+ip+" state:"+flag+"\r\n";
}
));
}

}


3 效果图

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: