【发布时间】:2016-10-07 13:05:30
【问题描述】:
在使用 TCP 制作用于远程控制 cisco 路由器的 c# 应用程序时,我遇到了等待路由器响应的问题。
对于应用程序,我必须使用 TCP 连接连接到 Cisco 路由器。建立连接后,网络流会将我的命令推送到 Cisco 路由器。为了让路由器处理命令,我使用Thread.Sleep。这不是最好的解决方案。
这是了解我的程序在做什么的完整代码。
string IPAddress = "192.168.1.1";
string message = "show running-config"; // command to run
int bytes;
string response = "";
byte[] responseInBytes = new byte[4096];
var client = new TcpClient();
client.ConnectAsync(IPAddress, 23).Wait(TimeSpan.FromSeconds(2));
if (client.Connected == true)
{
client.ReceiveTimeout = 3;
client.SendTimeout = 3;
byte[] messageInBytes = Encoding.ASCII.GetBytes(message);
NetworkStream stream = client.GetStream();
Console.WriteLine();
stream.Write(messageInBytes, 0, messageInBytes.Count()); //send data to router
Thread.Sleep(50); // temporary way to let the router fill his tcp response
bytes = stream.Read(responseInBytes, 0, responseInBytes.Length);
response = Encoding.ASCII.GetString(responseInBytes, 0, bytes);
return response; //whole command output
}
return null;
什么是获得完整响应的良好且可靠的方法。 感谢您的任何帮助或命令。
更多信息:
networksteam 总是充满了一些东西,大部分时间都充满了 cisco IOS 登录页面。最大的问题是确定路由器何时完成填充响应。 我大部分时间得到的回应:
"??\u0001??\u0003??\u0018??\u001f\r\n\r\n用户访问验证\r\n\r\n用户名:"
每次返回的数据都会不同,因为它是 cisco 命令的结果。这可以从短字符串到非常长的字符串。
- mrmathijs95 -
【问题讨论】:
-
我相信您的 stream.Read(..) 调用将阻塞,直到数据可用。您是否尝试过移除睡眠并检查您的应用程序是否仍然正常运行?
-
@peggy,
Stream.Read将阻止但不能 100% 确定您已读取所有数据。使用BinaryReader.Read阻塞直到预期的数据将被读取 -
这可能比法比奥的建议更完整:msdn.microsoft.com/en-us/library/bew39x2a(v=vs.110).aspx
-
@peggy 去掉 sleep 功能后,路由器的响应会是半空,只会得到 telnet 登录信息。
标签: c# .net networking network-programming