C4d
C4d

Reputation: 3292

C# TcpClient Timeout

Im trying to connect to my router inside local network. I've used the TcpClient so far.

Check my code:

public static void RouterConnect()
        {    
            TcpClient tcpClient = new TcpClient("192.168.180.1",23); <-- Timeout comes up here
            tcpClient.ReceiveTimeout = 2000; // Not working
            tcpClient.SendTimeout = 2000; // Also not working
            NetworkStream nStream = tcpClient.GetStream(); <-- thought Timeout would raise here

            // Further code here. But already tested while commented out. 
            // So everything else expect the code above shouldnt be relevant.
        }

I would like to add a settings-form (router-ip/user/password). Therefore there could be a fail on the user-side where the user types in a not existing host-ip.

The current timeout is at about 20 seconds which is way too high. TcpClient.ReceiveTimeout and TcpClient.SendTimeout arnt the right timeouts to set as I already tried it. Google wasnt helping me out with this.

So, anyone knows how to set the timeout in the right way for this? I've read about async. connections which I wouldnt like to use. A cleaner 1-line-timeout-set would be nice. Possible?

Thanks very much!

Edit 1: With a closer look while debugging I noticed, the timeout is already raising at the initialization of the tcpClient (as edited above in my code) not as I thought before at .GetStream().


EDIT SOLUTION:

As no one posted the working code from the solution I picked, here it is how its working:

public static void RouterConnect()
        {
            TcpClient tcpClient = new TcpClient();
            if(tcpClient.ConnectAsync("192.168.80.1",23).Wait(TimeSpan.FromSeconds(2)))
            {
                NetworkStream nStream = tcpClient.GetStream();
            }
            else
            {
                MessageBox.Show("Could not connect!");
            }
        }

Upvotes: 4

Views: 9510

Answers (3)

Or Harambam
Or Harambam

Reputation: 34

The only way i know is to use the Async methods. There is a nice new async method in .Net 4.5 which returns a Task that you could Wait like this:

tcpClient.ConnectAsync().Wait(timeout)

It returns a false if it doesn't succeed.

Upvotes: 1

Orel Eraki
Orel Eraki

Reputation: 12196

The current constructor overloading method your using is also connecting and thus blocking you until it get connected.

Furthermore, There are no properties on TcpClient to control the TcpClient timeout.

From MSDN: TcpClient(String, Int32)

Initializes a new instance of the TcpClient class and connects to the specified port on the specified host.

Alternative code from Social MSDN

using (vartcp = new TcpClient())  
{  
    IAsyncResult ar = tcp.BeginConnect("192.168.180.1", 23, null, null);  
    System.Threading.WaitHandle wh = ar.AsyncWaitHandle;  
    try 
    {  
       if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2), false))  
       {  
           tcp.Close();  
           throw new TimeoutException();  
       }  

        tcp.EndConnect(ar);  
    }  
    finally 
    {  
        wh.Close();  
    }  
} 

Upvotes: 0

darkfirewave
darkfirewave

Reputation: 82

Yeah the cleanest way I suppose would be to use the TcpClient.BeginConnect method.

So you would have a asynchronous feedback whether you could connect to the endpoint or not. Also see this: Async Connect

Upvotes: 0

Related Questions