这是我在stackoverflow上的第一篇文章,对不起任何事情。
关于我的范围:
private SshClient client;
private ForwardedPortDynamic port;
我有一个示例代码,用于连接类似于putty的ssh:
private void Connect()
{
try
{
client = new SshClient("myserverproxy.net", "user", "password");
client.KeepAliveInterval = new TimeSpan(0, 0, 60);
client.ConnectionInfo.Timeout = new TimeSpan(0, 0, 20);
client.Connect();
port = new ForwardedPortDynamic("127.0.0.1", 20141);
client.AddForwardedPort(port);
port.Exception += delegate(object sender, ExceptionEventArgs e)
{
Console.WriteLine(e.Exception.ToString());
};
port.Start();
}
catch (Exception)
{
throw;
}
}
此代码断开连接:
private void Disconnect()
{
try
{
port.Stop();
client.Disconnect();
}
catch (Exception)
{
throw;
}
}
我有一个按钮来调用方法“Connect()”,但一段时间后它断开连接并且不再工作。导致断开的原因是什么?我需要建立连接不确定的时间。
非常感谢!
答案 0 :(得分:0)
首先SshClient
是一次性的,因此需要使用using
关键字进行调用。像这样:
using (client = new SshClient("myserverproxy.net", "user", "password")) {
client.KeepAliveInterval = new TimeSpan(0, 0, 60);
client.ConnectionInfo.Timeout = new TimeSpan(0, 0, 20);
client.Connect();
port = new ForwardedPortDynamic("127.0.0.1", 20141);
...
}
其次,您阅读this建议您需要使用ForwardedPortLocal
代替ForwardedPortDynamic
。
答案 1 :(得分:0)
我无法尝试,但我会这样做:
public static void Start()
{
using (var client = new SshClient("myserverproxy.net", "user", "password"))
{
client.KeepAliveInterval = new TimeSpan(0, 0, 60);
client.ConnectionInfo.Timeout = new TimeSpan(0, 0, 20);
client.Connect();
ForwardedPortDynamic port = new ForwardedPortDynamic("127.0.0.1", 20141);
client.AddForwardedPort(port);
port.Exception += delegate(object sender, ExceptionEventArgs e)
{
Console.WriteLine(e.Exception.ToString());
};
port.Start();
}
}
public static void Main(string[] args)
{
Thread thread1 = new Thread(Start);
thread1.Start();
}
将KeepAliveInterval设置为30s可能会有帮助吗?