views:

123

answers:

2

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, and ReconnectTimer
  • 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 launches ReconnectTimer

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.

+1  A: 

If you have connection issues, you will always have exceptions. I think you have a sound outline, you just need to handle the exceptions. You could start with your own Socket class implemenation and write the TCPIP Server. Starter code is at MS:

http://msdn.microsoft.com/en-us/library/fx6588te(VS.71).aspx

The C# code is half way down the VB page.

Jess
A: 

The class you should use is "SocketAsyncEventArgs". I've used it in this project:

http://ts3querylib.codeplex.com/

Have a look at the AsyncTcpDispatcher class.

Scordo