Here is my many-years many times modified code for TCP asynchronous client.
It is able to detect connection loss (thanks to using keep alive values).

But now, I need to reconnect it to server automatically after any connection loss detection (any communication error or Disconnect() call).

It works fine with some simple SW TCP servers, when I stop them listening or disconnect my client from them. But, when I connect to some real devices and start to simulate possible errors, problems start.

For example, I disconnect client PC from network, then after some time of "reconnecting", application goes to connection state loop and hangs, specifically method OnDataReceived throws SocketException: ConnectionReset on iRx = stateObject.Socket.EndReceive(asyn); call.

As I am not adept at async code, I believe I do something very bad

Show more