前言
在上位机的开发过程中,有时需要增加一些心跳或者网络监控方式,利用Ping可以确定远程计算机是不可访问网络,日志记录异常情况,当然也可以扩展,比如:再把错误信息上报等。
1、效果
2、前台
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Label Content="监控IP地址:"/>
<TextBlock Text="{Binding CommIp}" Grid.Column="1"/>
<Label Content="监控间隔事件:" Grid.Row="0" Grid.Column="2"/>
<TextBlock Text="{Binding CommTime}" Grid.Column="4"/>
<Label Content="当前状态:" Grid.Row="1" Grid.Column="0" />
<TextBlock Text="{Binding StateInfo}" Grid.Row="1" Grid.Column="1" />
<Label Content="最近错误:" Grid.Row="1" Grid.Column="2" />
<TextBlock Text="{Binding ErrStr}" Grid.Row="1" Grid.Column="3" />
<RichTextBox Grid.Row="2" Grid.ColumnSpan="4" Background="Aquamarine" x:Name="tbLog"/>
</Grid>
3、后台
public partial class MainWindow : Window
{
private DataInfo dataInfo = new DataInfo();
private DispatcherTimer mTimer = null;
public MainWindow()
{
InitializeComponent();
this.DataContext = dataInfo;
dataInfo.CommIp = ConfigurationManager.AppSettings["CommIP"];
dataInfo.CommTime = Convert.ToInt32(ConfigurationManager.AppSettings["MarginTiem"]);
mTimer = new DispatcherTimer();
mTimer.Tick += MTimer_Tick;
mTimer.Interval = TimeSpan.FromMilliseconds(dataInfo.CommTime);
this.Loaded += MainWindow_Loaded;
this.Closing += MainWindow_Closing;
}
private void MainWindow_Closing(object sender, CancelEventArgs e)
{
mTimer.Stop();
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
mTimer.Start();
}
private void MTimer_Tick(object sender, EventArgs e)
{
IsPingSuccess();
}
public bool IsPingSuccess()
{
Ping ping = new Ping();
PingReply reply = ping.Send(dataInfo.CommIp, 1000);
if (reply.Status == IPStatus.Success)
{
dataInfo.StateInfo = "在线";
return true;
}
dataInfo.ErrStr = $"{DateTime.Now.ToString()}";
dataInfo.StateInfo = "离线";
WriteInfo(dataInfo.StateInfo);
return false;
}
private int num = 0;
private void WriteInfo(string msg)
{
num++;
if (this.Dispatcher.CheckAccess())
{
if (num >= 100)
{
tbLog.Document.Blocks.Clear();
}
tbLog.AppendText($"{DateTime.Now.ToString()} {msg}\r\n");
}
else
{
if (num >= 100)
{
tbLog.Document.Blocks.Clear();
}
this.Dispatcher.Invoke(() =>
{
tbLog.AppendText($"{DateTime.Now.ToString()} {msg}\r\n");
});
}
}
}
4、数据结构
public class DataInfo : INotifyPropertyChanged
{
private string commIp;
public string CommIp
{
get { return commIp; }
set { Set(ref commIp, value); }
}
private int commTime;
public int CommTime
{
get { return commTime; }
set { Set(ref commTime, value); }
}
private string errStr;
public string ErrStr
{
get { return errStr; }
set { Set(ref errStr, value); }
}
private string stateInfo = "UM";
public string StateInfo
{
get { return stateInfo; }
set
{
if (stateInfo != value)
{
WritInfo(value);
}
Set(ref stateInfo, value);
}
}
private void WritInfo(string info)
{
string path = $"{DateTime.Now.ToString("yyyy-MM-dd")}Record.txt";
string strinfo = DateTime.Now.ToString("HH:mm:ss fff ") + info;
using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
using (StreamWriter writer = new StreamWriter(fs))
{
writer.WriteLine(strinfo);
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void Set<T>(ref T item, T value, [CallerMemberName] string propertyName = null)
{
if (!EqualityComparer<T>.Default.Equals(item, value))
{
item = value;
}
OnPropertyChanged(propertyName);
}
protected void OnPropertyChanged([CallerMemberName] string propertyName = null) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}