Apollo3zehn / FluentModbus

Lightweight and fast client and server implementation of the Modbus protocol (TCP/RTU).
MIT License
189 stars 71 forks source link

ConnectionTimeout vs. MaxConnections in async ModbusTcpServer not working correctly #42

Closed mkroesen closed 3 years ago

mkroesen commented 3 years ago

I have found a problem in the combination of MaxConnections and ConnectionTimeout (ModbusTcpServer).

The following function only works if server.IsAsynchronous = false. https://github.com/Apollo3zehn/FluentModbus/blob/master/src/FluentModbus/Server/ModbusTcpServer.cs#L172

I have server.MaxConnections = 5 and server.ConnectionTimeout = 5sec. I can successfully establish 5 connections to the server, then is server.ConnectionCount = 5. If I disconnect one of the 5 connections, server.ConnectionCount should be 4 after ConnectionTimeout but it is 5, only in the synchronous mode it is 4.

For your information: even after a long time a ModbusTcpRequestHandler is not removed. I have been continuously logging server.ConnectionCount in to the console and the value 5 has not changed. Even if I disconnected all 5 connections I was not able to establish a new one, so the server had to be reinitialized.

The whole thing unfortunately only works in the synchronous mode of the ModbusTcpServer.

I'm not sure if I made a mistake, it would be great if you could look over it.

Apollo3zehn commented 3 years ago

Thanks for reporting this, I will look at it tomorrow.

Apollo3zehn commented 3 years ago

The problem was that an exception was caused within the long running "client-removal" task which stopped that task without any notification. The exception itself was thrown when the client was about to be removed. The code asked the ModbusTcpRequestHandler for its name to write a log message. This name was constructed using the IP address info of the already disposed TCP client which led to an ObjectDisposedException.

I have changed this, so the name is created only once in ModbusTcpRequestHandler constructor and I added a Try-Catch block to prevent that the Task is stopped silently by exceptions like this in future.

Apollo3zehn commented 3 years ago

I hope this was the root cause of your problem :)

mkroesen commented 3 years ago

I tested it with the new version and it works perfectly. Thanks for your work.