private void but_open_Click(object sender, EventArgs e) { try { client?.Close(); if (chb_rtudata.Checked) { client = new ModBusTcpRtuClient(txt_ip.Text?.Trim(), int.Parse(txt_port.Text?.Trim())); } else { client = new ModBusTcpClient(txt_ip.Text?.Trim(), int.Parse(txt_port.Text?.Trim())); } var result = client.Open(); if (result.IsSucceed) { but_read.Enabled = true; but_write.Enabled = true; but_open.Enabled = false; but_close.Enabled = true; but_sendData.Enabled = true; AppendText($"连接成功"); } else { MessageBox.Show($"连接失败:{result.Err}"); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void but_sendData_Click(object sender, EventArgs e) { try { if (string.IsNullOrWhiteSpace(txt_dataPackage.Text)) { MessageBox.Show("请输入要发送的报文"); return; } var dataPackageString = txt_dataPackage.Text.Replace(" ", ""); if (dataPackageString.Length % 2 != 0) { MessageBox.Show("请输入正确的的报文"); return; } var dataPackage = DataConvert.StringToByteArray(txt_dataPackage.Text?.Trim(), false); var msg = client.SendPackage(dataPackage); AppendText($"[请求报文]{string.Join(" ", dataPackage.Select(t => t.ToString("X2")))}"); AppendText($"[响应报文]{string.Join(" ", msg.Select(t => t.ToString("X2")))}\r\n"); } catch (Exception ex) { MessageBox.Show(ex.Message); client.Close(); client.Open(); } }