【发布时间】:2015-10-04 23:01:32
【问题描述】:
我正在尝试连接到本地网络内的路由器。到目前为止,我已经使用了 TcpClient。
检查我的代码:
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.
}
我想添加一个设置表单(router-ip/user/password)。因此,在用户输入不存在的主机 IP 的情况下,用户端可能会失败。
当前的超时时间约为 20 秒,这太高了。 TcpClient.ReceiveTimeout 和 TcpClient.SendTimeout 没有设置正确的超时时间,因为我已经尝试过了。 Google 没有帮我解决这个问题。
那么,有人知道如何为此设置正确的超时时间吗?我读过异步。我不想使用的连接。一个更干净的 1-line-timeout-set 会很好。可能吗?
非常感谢!
编辑 1:
在调试时仔细观察,我注意到超时已经在 tcpClient 的初始化(如上面在我的代码中编辑的那样)提高,而不是我之前在.GetStream() 认为的那样。
编辑解决方案:
由于没有人发布我选择的解决方案中的工作代码,因此它是如何工作的:
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!");
}
}
【问题讨论】:
-
你在哪里从流中读取?
-
它稍后出现,但我猜不相关。我评论了阅读。超时出现在我上面在 tcpClient 初始化时编辑的代码中。
-
TcpClient的构造函数还有connects the client 到端点。 -
@cubrr 是的,谢谢。大约5分钟前才注意到。无论如何,我的问题保持不变。
-
我想你的问题类似于this one。如果您的目标是 .NET 4.5,this answer 可能会成功。
标签: c# timeout tcpclient networkstream socketexception