Kale Muscarella
Kale Muscarella

Reputation: 97

Connect to server, maintain connection, and keep retrying if connection is ever lost?

I want my client application to connect to my server application, and continuously try to re-connect if the connection is ever lost.

I am currently trying to use a timer to check the connection every second by first attempting to send a packet with NetworkStream.Write and then checking TcpClient.Connected, but it doesn't seem to be working. TcpClient.Connected never goes back to false after the client loses connection.

What would be the simplest way of doing this?

Upvotes: 2

Views: 2433

Answers (1)

Despertar
Despertar

Reputation: 22362

If the connection is closed it should throw an exception. You can catch it and and re-open the connection. Here is an exception I got by shutting down a TcpListener while a TcpClient was connected.

System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host

Edit: Here is a sample of how you could continuously re-try to connect. Note depending on your situation you may want to have a counter or timer so that it does not re-try forever.

public class PersistantTcpClient
{
    TcpClient Client { get; set }

    public void Start()
    {
        while (true)
        {
             try
             {
                this.Client.Connect("host", port)

                // once it can connect, get back to work!
                DoWork();
             }
             catch (SocketException)
             {
                // if it cannot connect, keep trying
             }
        }
    }
}

Upvotes: 3

Related Questions