简体   繁体   English

C#TcpClient超时

[英]C# TcpClient Timeout

Im trying to connect to my router inside local network. 我试图连接到本地网络内的路由器。 I've used the TcpClient so far. 到目前为止,我已经使用了TcpClient。

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). 我想添加一个设置表单(router-ip / user / password)。 Therefore there could be a fail on the user-side where the user types in a not existing host-ip. 因此,在用户端,如果用户键入不存在的host-ip,可能会出现故障。

The current timeout is at about 20 seconds which is way too high. 当前超时大约是20秒 ,这太高了。 TcpClient.ReceiveTimeout and TcpClient.SendTimeout arnt the right timeouts to set as I already tried it. TcpClient.ReceiveTimeoutTcpClient.SendTimeout设置了正确的超时设置,因为我已经尝试过了。 Google wasnt helping me out with this. Google并没有帮助我。

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. 更干净的1行超时设置会很好。 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() . 编辑1:在调试时仔细观察,我发现tcpClient的初始化超时已经提高了(如我在上面的代码中编辑的),而不是我以前在.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!");
            }
        }

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: .Net 4.5中有一个不错的新异步方法,它返回一个可以等待的Task,如下所示:

tcpClient.ConnectAsync().Wait(timeout)

It returns a false if it doesn't succeed. 如果不成功,则返回false。

Yeah the cleanest way I suppose would be to use the TcpClient .BeginConnect method. 是的,我想最干净的方法是使用TcpClient .BeginConnect方法。

So you would have a asynchronous feedback whether you could connect to the endpoint or not. 因此,无论是否可以连接到端点,您都会收到异步反馈。 Also see this: Async Connect 另请参见: 异步连接

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. 此外TcpClient上没有用于控制TcpClient超时的属性。

From MSDN : TcpClient(String, Int32) MSDNTcpClient(String, Int32)

Initializes a new instance of the TcpClient class and connects to the specified port on the specified host. 初始化TcpClient类的新实例,并连接到指定主机上的指定端口。

Alternative code from Social MSDN 来自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();  
    }  
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM