static void Main(string[] args) { try { using (TcpClient client = new TcpClient("127.0.0.1", 502)) { client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); ModbusTcpMaster master = ModbusTcpMaster.CreateTcp(client); // read five input values ushort startAddress = 100; ushort numInputs = 5; bool[] inputs = master.ReadInputs(startAddress, numInputs); for (int i = 0; i < numInputs; i++) Console.WriteLine("Input {0}={1}", startAddress + i, inputs[i] ? 1 : 0); while (true) { } } } catch (Exception e) { Console.WriteLine(e.Message); } }
/// <summary> /// 连接到Robot /// </summary> /// <param name="ip"></param> public void Connect(string ip) { if (ip.Length == 0) { return; } try { client = new TcpClient(ip, 502); client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); master = ModbusTcpMaster.CreateTcp(client); isBusy = false; TxtIP.Text = ip; } catch (Exception x) { ShowStatus("Modbus 连接失败!" + x.Message, false); if (client != null) { client.Close(); } client = null; } }