我正在尝试连接到本地网络内的路由器。到目前为止,我已经使用了 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.
}
我想添加一个设置表单(路由器 IP/用户/密码)。因此,在用户输入不存在的主机 ip 的情况下,用户端可能会失败。
当前超时时间约为 20 秒 这太高了。
TcpClient.ReceiveTimeout
和 TcpClient.SendTimeout
设置正确的超时时间,因为我已经尝试过了。谷歌没有帮助我解决这个问题。那么,有人知道如何为此以正确的方式设置超时吗?我读过异步。我不想使用的连接。一个更干净的 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!");
}
}
最佳答案
我知道的唯一方法是使用异步方法。
.Net 4.5 中有一个不错的新异步方法,它返回一个任务,您可以像这样等待:
tcpClient.ConnectAsync().Wait(timeout)
如果不成功,则返回 false。
关于C# TcpClient 超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31438291/