C# 判断设备是否在线

来源:互联网 发布:贵州大数据产业规模 编辑:程序博客网 时间:2024/05/22 10:52

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 效果图


1 0
原创粉丝点击