C# 判断设备是否在线

    xiaoxiao2022-07-13  158

    1  ping类 //From:www.uzhanbao.com

    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";             }            ));         }       } ?

    最新回复(0)