日期:2014-05-20  浏览次数:20746 次

断线后自动重新连接
有一个程序需要长时间的连接网络,比如说下载工具。但是网络状况不好的话会断线,请问大家有谁知道怎么能够在检测到断线之后,自动重新连接网络。用C#怎么实现。最好能有一些程序示例。谢谢大家了。

------解决方案--------------------
建立一个心跳,定时触发
------解决方案--------------------
做个轮询 不断监听 只要一断线就做连接操作!

------解决方案--------------------
用try catch捕捉异常断线,在catch中重写连接程序
------解决方案--------------------
给你一个检测网络方法:
可以创建一个Timer,定时检测,如果你的程序能Catch到断网后的异常,就写在Catch里面.

public static string CmdPing(string strIp)
{
Process p = new Process();

p.StartInfo.FileName = "cmd.exe ";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
string pingrst;

p.Start();
p.StandardInput.WriteLine( "ping -n 1 " + strIp);
p.StandardInput.WriteLine( "exit ");

string strRst = p.StandardOutput.ReadToEnd();

if (strRst.IndexOf( "(0% loss) ") != -1)
pingrst = "Connect successfully. ";
else if (strRst.IndexOf( "Destination host unreachable. ") != -1)
pingrst = "Destination host unreachable. ";
else if ((strRst.IndexOf( "Request timed out. ") != -1) | (strRst.IndexOf( "(100% loss) ") != -1))
pingrst = "Request timed out. ";
else if (strRst.IndexOf( "Unknown host ") != -1)
pingrst = "Unknown host ";
else
pingrst = strRst;

p.Close();

return pingrst;
}