using
System;
using
System.Collections.Generic;
using
System.Data;
using
System.Linq;
using
System.Threading;
using
System.Windows.Forms;
using
System.Net.Sockets;
using
System.Net;
namespace
心跳测试
{
public
partial
class
Form1 : Form
{
public
Form1()
{
InitializeComponent();
}
Dictionary<
string
, DateTime> dicComputer =
new
Dictionary<
string
, DateTime>();
private
void
Form1_Load(
object
sender, EventArgs e)
{
new
Thread(() =>
{
UdpClient uc =
new
UdpClient(
new
IPEndPoint(IPAddress.Any, 5467));
uc.Client.ReceiveTimeout = 4000;
while
(
true
)
{
try
{
IPEndPoint ipEndPoint =
null
;
byte
[] bytes = uc.Receive(
ref
ipEndPoint);
this
.Invoke((EventHandler)
delegate
{ textBox1.Text =
string
.Empty; });
string
computer = ipEndPoint.Address.ToString();
if
(!dicComputer.ContainsKey(computer))
dicComputer.Add(computer, DateTime.Now);
else
dicComputer[computer] = DateTime.Now;
dicComputer = dicComputer.Where(x => (DateTime.Now - x.Value).Seconds < 4).ToDictionary(x => x.Key, x => x.Value);
foreach
(
var
onlineComputer
in
dicComputer)
{
this
.Invoke((EventHandler)
delegate
{
textBox1.AppendText(onlineComputer +
" 电脑在线"
+ Environment.NewLine);
});
}
}
catch
(Exception ex)
{
this
.Invoke((EventHandler)
delegate
{ textBox1.Text =
"没有电脑在线"
; });
}
}
})
{ IsBackground =
true
}.Start();
}
}
}