Search code examples
c#exceptionnetwork-programmingmodbus-tcp

EasyModbus: disconnecting from network doesn't change the connection state


In a C# application I use EasyModbus to connect to a remote server:

ModbusClient client = new ModbusClient()
{
    IPAddress = "192.168.1.100",
    Port = 502,
    ConnectionTimeout = 200
}

try
{
    client.Connect();
}
catch (EasyModbus.Exceptions.ConnectionException)
{
    throw;
}
catch (System.Net.Sockets.SocketException)
{
    throw;
}

then in other parts of my application I try to read/write only if the client is still connected:

if (client.Connected)
{
    try
    {
        int[] readHoldingRegisters = client.ReadHoldingRegisters(1000, 10);
        // do something
    }
    catch (Exception)
    {
        throw;
    }
}

If while the application is running I disconnect my laptop from the WiFi network, the Connected property is still true even after a long time. I get a "out of range" exception when I try to read the registers, but I wonder why that property doesn't turn to false immediately. At least, I would expect a "timeout" exception when I try to read/write something.

Is there a better approach to know the server is not reachable anymore?


Solution

  • It is actually not possible to detect a connection loss if the server has simply been disconnected without closing the connection. Then the Connected property is still true.

    Maybe the Available method could be helpful. That method simply polls the server if it is still alive.