In order to learn how to use Modbus, I've been trying to set up two computers I have to communicate between each other. I have them connected via an Ethernet cable, and have an instance of Visual studio running C# on each of them. I've attached both codes below, which are snippets from the NMODBUS sample program on github. Master:
using (TcpClient client = new TcpClient("127.0.0.1", 502))
{
var factory = new ModbusFactory();
IModbusMaster master = factory.CreateMaster(client);
// read five input values
ushort startAddress = 100;
ushort numInputs = 5;
bool[] inputs = master.ReadInputs(0, startAddress, numInputs);
for (int i = 0; i < numInputs; i++)
{
Console.WriteLine($"Input {(startAddress + i)}={(inputs[i] ? 1 : 0)}");
}
Slave: //
// create and start the TCP slave
int port = 502;
IPAddress address = new IPAddress(new byte[] { 127, 0, 0, 1 });
TcpListener slaveTcpListener = new TcpListener(address, port);
slaveTcpListener.Start();
IModbusFactory factory = new ModbusFactory();
IModbusSlaveNetwork network = factory.CreateSlaveNetwork(slaveTcpListener);
IModbusSlave slave1 = factory.CreateSlave(1);
IModbusSlave slave2 = factory.CreateSlave(2);
network.AddSlave(slave1);
network.AddSlave(slave2);
network.ListenAsync().GetAwaiter().GetResult();
// prevent the main thread from exiting
Thread.Sleep(Timeout.Infinite);
Github: https://github.com/NModbus/NModbus
The slave code runs as expected, but the master code compiles, but then throws this error: System.Net.Sockets.SocketException: 'No connection could be made because the target machine actively refused it 127.0.0.1:502'
I'm confident that the code snippets are correct, and am currently convinced that the problem is that these two computers aren't actually talking with one another. What do I have to change to get the communication working?