问题描述
我正在编写一个程序,以通过cmd从另一台计算机控制一台计算机。当我想确保主机启动时遇到了一个问题。
try
{
using (TcpClient client = new TcpClient(IP,portNumber))
{
using (Stream stream = client.GetStream())
{
using (StreamReader rdr = new StreamReader(stream))
{
streamWriter = new StreamWriter(stream);
StringBuilder strInput = new StringBuilder();
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardError = true;
p.OutputDataReceived += new DataReceivedEventHandler(CmdOutputDataHandler);
p.Start();
p.BeginOutputReadLine();
while (true)
{
strInput.Append(rdr.ReadLine());
strInput.Append("\n");
p.StandardInput.WriteLine(strInput);
strInput.Remove(0,strInput.Length);
}
}
}
}
}
catch (Exception e )
{
Console.WriteLine(e);
}
这是tcp远程连接的代码。独立运行非常好。现在,我尝试修改它,以便它将尝试连接,直到建立连接为止。因此,我添加了一个while循环和一个PingHost方法来对特定端口上的主机执行ping操作:
string IP = "My_IP_for_testing";
int portNumber = 1234;
bool available = PingHost(IP,portNumber);
while (available == false)
{
Thread.Sleep(500);
available = PingHost(IP,portNumber);
Console.WriteLine("Failure");
}
Console.WriteLine("Success");
try
{
using (TcpClient client = new TcpClient(IP,strInput.Length);
}
}
}
}
}
catch (Exception e )
{
Console.WriteLine(e);
}
}
private static void CmdOutputDataHandler(object sendingProcess,DataReceivedEventArgs outLine)
{
StringBuilder strOutput = new StringBuilder();
if (!String.IsNullOrEmpty(outLine.Data))
{
try
{
strOutput.Append(outLine.Data);
streamWriter.WriteLine(strOutput);
streamWriter.Flush();
}
catch (Exception ex)
{
// silence is golden
}
}
}
public static bool PingHost(string hostURI,int portNumber)
{
try
{
using (TcpClient client = new TcpClient(hostURI,portNumber))
client.Client.Disconnect(true);
return true;
}
catch
{
return false;
}
}
}
}
引发的异常与无法与我发布的第一个代码示例建立连接相同(主机未启动,ExtendedSocketException(10061))。我希望你能帮助我! 祝你有美好的一天!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)