TcpClient Auto-Reconnect

Kai picture Kai · May 31, 2011 · Viewed 11.3k times · Source

What is the best way to make a Tcpclient auto reconnect to the server when it's disconnected (e.g. by the server itself)?

The code I'm currently using is:

public void ClientWork()
{
        TcpClient client = new TcpClient();

        try
        {
            try
            {
                client.Connect(ip, port);
            }
            catch(Exception ex)
            {
                logger.ErrorFormat("client.Connect: {0}", ex.Message);
                return false;
            }

            NetworkStream ns = client.GetStream();
            byte[] buff;

            while (__bRunning)
            {
                buff = new byte[1000];
                ns.Read(buff, 0, 1000);

                string line = System.Text.Encoding.Default.GetString(buff);
            }

            //ns.Close();
            client.Close();
        }
        catch(Exception e)
        {
            //Reconnect?
            client.Close();
            client = null;

            return false;
        }
}

I'm using C# .NET

Answer

user90150 picture user90150 · May 31, 2011

There is no events available to get notification for broken connection.

There could be 2 possible solution.

  1. Polling. You have separate thread that try to poll socket continually done in different thread. Refer Instantly detect client disconnection from server socket

  2. If you have low level control over socket or the interface which is using socket, you can do try..catch for read and write methods or try..catch for wrappers of read and write methods and when there is any exception you can re-connect and try to read and write.