private void btnMbSend_Click(object sender, EventArgs e) { var sd = ModBus.HexStrToHexByte(txtMbData.Text.Trim());//开 _serverSocket.Send(sd, sd.Length, 0); ShowMsg("已发送:" + txtMbData.Text.Trim()); }
private void btnSend_Click(object sender, EventArgs e) { if (cmbFunc.SelectedIndex == 1)//读 { var sd = ModBus.ModBusWrite(int.Parse(txtSlave.Text.Trim()), ModBus.ModBusFunction.WriteCoil, int.Parse(txtAddr.Text.Trim()), cmbData.SelectedIndex == 0);//写数据 _serverSocket.Send(sd, sd.Length, 0); ShowMsg("已发送:" + ModBus.HexByteToHexStr(sd)); } else//写 { var sd = ModBus.ModBusRead(int.Parse(txtSlave.Text.Trim()), ModBus.ModBusFunction.ReadCoils, int.Parse(txtAddr.Text.Trim()), 1);//写数据 _serverSocket.Send(sd, sd.Length, 0); ShowMsg("已发送:" + ModBus.HexByteToHexStr(sd)); } }
private void ListenSlave(object s) { try { byte[] recByte = new byte[1024]; while (true) { var bytes = _serverSocket.Receive(recByte, recByte.Length, 0); var rcvbt1 = new byte[bytes]; Array.Copy(recByte, 0, rcvbt1, 0, bytes); var rst = ModBus.HexByteToHexStr(rcvbt1); ShowMsg(!rst.StartsWith("33") ? "收到消息:" + Encoding.UTF8.GetString(rcvbt1) : "收到消息:" + rst);//33开头的属于modbus码 } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private static string WriteRead(string hexdata, Socket serverSocket) { byte[] recByte = new byte[1024]; var sd = ModBus.HexStrToHexByte(hexdata);//开 serverSocket.Send(sd, sd.Length, 0); int bytes = serverSocket.Receive(recByte, recByte.Length, 0); var rcvbt1 = new byte[bytes]; Array.Copy(recByte, 0, rcvbt1, 0, bytes); var rst = ModBus.HexByteToHexStr(rcvbt1); var s = rst.Replace("7777772E7573722E636E", ""); if (s == "")//排除第一个空 { bytes = serverSocket.Receive(recByte, recByte.Length, 0); rcvbt1 = new byte[bytes]; Array.Copy(recByte, 0, rcvbt1, 0, bytes); rst = ModBus.HexByteToHexStr(rcvbt1); s = rst.Replace("7777772E7573722E636E", ""); } return(s); }