我正在尝试在本地网络内连接我的路由器。到目前为止,我已经使用了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:通过仔细调试,我注意到在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!");
}
}