我试图在本地网络中连接到我的路由器。到目前为止,我已经使用了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行超时设置会很好。有可能吗?
非常感谢!
编辑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!");
}
}https://stackoverflow.com/questions/31438291
复制相似问题