using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net.Sockets; using System.Net; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using static System.Windows.Forms.VisualStyles.VisualStyleElement; using System.Threading; using DataCapture_MA.log4Net; using DataCapture_MA.Entity; using DataCapture_MA.DataHnadle; using DataCapture_MA.AutoMapperConfig; using System.IO; using IWshRuntimeLibrary; namespace DataCapture_MA { public partial class CaptrueForm : Form { bool RunningFlag = false; Socket skt = WZ.Useful.Commons.NetworkUtil.CreateUdpSocket(); EndPoint RemotePoint = null; public delegate void MyInvoke(string strRecv); public CaptrueForm() { InitializeComponent(); var hostName = Dns.GetHostName(); var ips = Dns.GetHostAddresses(hostName); string targetSubnet = "10.133.13"; // 目标网段 bool foundTargetSubnet = false; foreach (var ip in ips) { if (ip.AddressFamily == AddressFamily.InterNetwork) // 只显示IPv4地址 { ipSelect.Items.Add(ip); // 检查是否包含目标网段 if (ip.ToString().StartsWith(targetSubnet)) { ipSelect.SelectedItem = ip; // 选中匹配的 IP foundTargetSubnet = true; } } } if (!foundTargetSubnet && ipSelect.Items.Count > 0) { //MessageBox.Show($"未找到网段为 {targetSubnet} 的IP地址,将默认选中第一个IP。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); ipSelect.SelectedIndex = 0; } to_ipTxt.Text = ipSelect.SelectedItem?.ToString(); // 初始化 AutoMapper AutoMapper.Mapper.Initialize(cfg => { cfg.AddProfile(); }); // 创建快捷方式 string shortcutName = "MaDataCapture"; // 快捷方式名称 string targetPath = Application.ExecutablePath; // 程序路径 string startupPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup); // 启动文件夹路径 CreateShortcut(shortcutName, targetPath, startupPath); // 创建快捷方式 if (ipSelect.Items.Count > 0) { StartReceive(); // 启动程序 CreateDatabase(); // 初始化数据库 } // 删除一个月前的数据 new Thread(AutoDeleteHistoryDate.Handler).Start(); } public static void CreateShortcut(string shortcutName, string targetPath, string startupPath) { string shortcutPath = Path.Combine(startupPath, shortcutName + ".lnk"); if (System.IO.File.Exists(shortcutPath)) return; WshShell shell = new WshShell(); IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath); shortcut.TargetPath = targetPath; shortcut.WorkingDirectory = Path.GetDirectoryName(targetPath); shortcut.Save(); } private void ReceiveHandle() { //接收数据处理线程 string msg; byte[] data = new byte[204800]; MyInvoke myI = new MyInvoke(UpdateRcvTextBox); while (RunningFlag) { if (skt == null || !RunningFlag || skt.Available < 1) { Thread.Sleep(200); continue; } //跨线程调用控件 //接收UDP数据报,引用参数RemotePoint获得源地址 int rlen = skt.ReceiveFrom(data, ref RemotePoint); msg = Encoding.Default.GetString(data, 0, rlen); r_showBox.BeginInvoke(myI, new object[] { "From " + RemotePoint.ToString() + " << " + msg }); } } //处理接收到的UDP private void UpdateRcvTextBox(string msg) { //接收数据显示 this.r_showBox.Text += (msg) + "\n\n"; Log4NetHelper.WriteInfoLog(LogType.Receive, msg); ReceiveDataHandle.AnalysisMeassage(msg); } private void start_connect_Click(object sender, EventArgs e) { StartReceive(); } public void StartReceive() { try { if (skt != null) { skt.Close(); skt.Dispose(); } // 创建新的 UDP 套接字 skt = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); // 设置允许重用地址和端口 skt.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); //得到本机IP,设置UDP端口号 IPAddress ip = IPAddress.Parse(ipSelect.SelectedItem.ToString());//本机IP int port = int.Parse(local_port.Text.Trim());//端口号 IPEndPoint iPEndPoint = new IPEndPoint(ip, port); skt.Bind(iPEndPoint); //得到客户机IP IPAddress ip2 = IPAddress.Parse(to_ipTxt.Text.Trim());//客户机IP int port2 = int.Parse(to_portTxt.Text.Trim());//端口号 IPEndPoint iPEndPoint2 = new IPEndPoint(ip2, port2); RemotePoint = (EndPoint)(iPEndPoint2); RunningFlag = true; Thread thread = new Thread(new ThreadStart(ReceiveHandle)); thread.Start(); Log4NetHelper.WriteInfoLog(LogType.Receive, "开启UDP通信成功" + iPEndPoint.ToString()); //ipSelect.Enabled = false; local_port.Enabled = false; to_ipTxt.Enabled = false; to_portTxt.Enabled = false; start_connect.BackColor = Color.DarkRed; start_connect.Enabled = false; colse_connect.BackColor = Color.DarkGreen; colse_connect.Enabled = true; r_showBox.Text += "数据接收已启动\n"; } catch (Exception ex) { Log4NetHelper.WriteInfoLog(LogType.Receive, "开启UDP通信失败" + ex); MessageBox.Show(ex.Message); } } private void CreateDatabase() { try { using (var context = new DbModel()) { // 确保数据库和表存在,如果不存在则创建 context.Database.EnsureCreated(); // 添加一些数据 context.RobotInfo.Add(new RobotInfo { WarnningNum = 0, //RobotStatus = "Normal", RobotModel = "Model X", RobotSerialNo = "123456", WarnningContent = "清除富文本框数据", CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), CreateStamp = DateTimeOffset.Now.ToUnixTimeSeconds(), IsDelete = false }); // 保存更改 context.SaveChanges(); var xx = context.RobotInfo.ToList(); } } catch (Exception ex) { r_showBox.Text = "数据库初始化异常"+ ex.Message; } } private void colse_connect_Click(object sender, EventArgs e) { try { RunningFlag = false; // 停止接收线程 if (skt != null) { skt.Close(); // 关闭套接字 } ipSelect.Enabled = true; local_port.Enabled = true; to_ipTxt.Enabled = true; to_portTxt.Enabled = true; colse_connect.Enabled = false; start_connect.Enabled = true; colse_connect.BackColor = Color.DarkRed; start_connect.BackColor = Color.DarkGreen; r_showBox.Text += "已关闭数据接收\n"; } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void sendbtn_Click(object sender, EventArgs e) { try { string sendStr = richSendTxt.Text; IPAddress ip2 = IPAddress.Parse(to_ipTxt.Text.Trim());//客户机IP int port2 = int.Parse(to_portTxt.Text.Trim());//端口号 IPEndPoint iPEndPoint2 = new IPEndPoint(ip2, port2); RemotePoint = (EndPoint)(iPEndPoint2); skt.Connect(RemotePoint); skt.Send(WZ.Useful.Commons.ConvertHelper.StringToBytes(sendStr)); r_showBox.Text += "To " + RemotePoint.ToString() +">> " + (sendStr) + "\n"; } catch( Exception ex) { MessageBox.Show(ex.Message); } } private void clearBtn_Click(object sender, EventArgs e) { CreateDatabase(); richSendTxt.Text = string.Empty; r_showBox.Text = string.Empty; } private void ipSelect_SelectedIndexChanged(object sender, EventArgs e) { } } }