1:應用程序界面
2:實現的功能
(1)常規的UDP收發操作
(2)私有通信協議的格式轉化
(3)數據的定時刷新顯示和實時存儲(txt)
(4)數據的歷史曲線查看
3:實現的方式
UDP設置的核心代碼
private void btnStart_Click(object sender, EventArgs e)
{
ReceiveMessageThread = new Thread(ReceiveMessage);
ReceiveMessageThread.IsBackground = true;
if (btnStart.Text == "啓動")
{
btnStart.Text = "已啓動";
rec_flag = true;
//創建並啓動消息接收線程
ReceiveMessageThread.Start();
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(GetLocalIP()), Convert.ToInt32(monitor_Port.Text));
//實例化UDP客戶端
myUdpClient = new UdpClient(ipEndPoint);
}
else
{
btnStart.Text = "啓動";
ReceiveMessageThread.Abort();
try
{ ReceiveMessageThread.Join(); }
catch (ThreadAbortException)
{
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
rec_flag = false;
myUdpClient.Close();
}
}
定時刷新顯示的核心代碼:
private void refresh_curve()
{
while (true)
{
string test_time = DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss");
string Path1 = "";
if (starttime == "")
{
Path1 = get_latest_file(Datapath);
}
else
{
Path1 = @".\data\" + starttime + ".txt";
}
// 從文件中讀取並顯示每行
string line = "";
try
{
using (StreamReader sr = new StreamReader(Path1))
{
SortedList sl = new SortedList();
while ((line = sr.ReadLine()) != null)
{
string[] array = line.Split('+');
sl.Add(array[0], array[1]);
}
// 獲取鍵的集合
ICollection key = sl.Keys;
foreach (string k in key)
{
// Console.WriteLine(k + ": " + sl[k]);
Time_axis.Add(k);
Curve.Add(sl[k].ToString().Split(',')[type_curve]);
}
}
}
catch
{
using (StreamReader sr = new StreamReader(get_latest_file(Datapath)))
{
SortedList sl = new SortedList();
while ((line = sr.ReadLine()) != null)
{
string[] array = line.Split('+');
sl.Add(array[0], array[1]);
}
// 獲取鍵的集合
ICollection key = sl.Keys;
foreach (string k in key)
{
// Console.WriteLine(k + ": " + sl[k]);
Time_axis.Add(k);
Curve.Add(sl[k].ToString().Split(',')[type_curve]);
}
}
Console.WriteLine("沒有當前時間段數據:" + Path1);
}
//建立委託機制,防止線程間異常
chart1.Invoke(new EventHandler(delegate
{
chart1.Series[0].Points.DataBindXY(Time_axis, Curve);
chart1.Series[0].Name = chart_series_name[type_curve];
}));
Thread.Sleep(3000);
Time_axis.Clear();
Curve.Clear();
}
}
4:2個模擬客戶端發送與接收數據