I have to write a TCP Client
that will have ability to reconnect to server. The server can be unavailable due to poor network connection quality or some maintenance issues. I'm searching for quality solutions in this area.
My current solutions is following:
- keep connection state in ConnectionState enum {Offline, Online, Connecting}
- create client with
TcpClient
class. - create two timers called
ConnectionCheckTimer
, andReconnectTimer
- connect to server
- start reader thread and connection check timer
- reading is performed with tcpClient.GetStream() and then reading from this stream
- when Exception is caught in readerLoop client state is changed to offline and ReconnectTimer is launched
ConnectionCheckTimer
periodically checks lastMessageTimestamp and compares it with current time if the interval is greater then maxValue it launchesReconnectTimer
Currently i'm not satisfied with this solution because it still generates exceptions for instance ObjectDisposedException on TcpClient.NetworkStream. I'm looking for some clean and reusable Tcp reconnecting client implementation that is able to cope with all sockets problems that can occur during connecting, disconnecting, reading data.