rossmann-engineering / EasyModbusTCP.NET

Modbus TCP, Modbus UDP and Modbus RTU client/server library for .NET implementations
928 stars 402 forks source link

Flush network stream recieve buffer before starting request #55

Open lukasfischer83 opened 3 years ago

lukasfischer83 commented 3 years ago

I am trying to recover from connection losses (unplug cable, plug back in).

Symptom: I get answers to old requests instead of the current one after the connection is reestablished.

How to reproduce: After loosing connection I try reconnecting until success. Then reading continues.

Solution This seems to be fixed by making sure, that the revieve buffer of stream is empty before sending a request in for example ReadHoldingRegisters() in the ModbusClient class:

while (stream.DataAvailable) // flush old rcv buf { Byte[] trash = new Byte[256]; Console.WriteLine("{0} bytes Garbage read from stream", stream.Read(trash, 0, 256)); }

Using VS Express 2015 and .NET 4.5