1

This is my first post on stackoverflow, sorry for anything.

On my scope:

private SshClient client;
private ForwardedPortDynamic port;

I have a sample code to connect with ssh similar at putty:

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;
        }
    }

And this code to disconnect:

private void Disconnect()
    {
        try
        {
            port.Stop();
            client.Disconnect();
        }
        catch (Exception)
        {

            throw;
        }
    }

I have a button to call method "Connect()", but after some time it disconnect and don't work anymore. What is causing the disconnect? I need establish connect for undetermined time.

Thanks a lot!

2 Answers2

0

First SshClient is disposable so needs to be called using the using keyword. Something like this:

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);
    ...
}

Second, have you read this suggests you need to use ForwardedPortLocal instead of ForwardedPortDynamic.

Community
  • 1
  • 1
Jack Hughes
  • 5,514
  • 4
  • 27
  • 32
0

I can't try this but I would do it in this way:

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();
}

Maybe it helps to set KeepAliveInterval to 30s?

c0d3b34n
  • 534
  • 7
  • 14