I want to display the live connection status in my console application. The problem is that I'm stuck in a loop and I have no idea how to check correctly the connection status while I'm looping. When the connection is lost (in most cases about ~4min) I want to wait until the connection is back again. Online and Offline time should be displayed in the console all the time.
Thanks for any ideas or help!
using WinSCP;
using (Session session = new Session())
{
try
{
int i = 0;
// Session Config
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = "xxx.xx.xx.xx",
UserName = "xxxxxx",
Password = "xxxxxxxxx",
SshHostKeyFingerprint = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
};
// Connect
session.Open(sessionOptions);
while (true)
{
if (session.Opened == true) //this is displayed all the time
{
Console.WriteLine(i++ + " " + DateTime.Now + " " + "Online");
// check again here if session.Opened still true?
}
else if (session.Opened == false)
{
Console.WriteLine(i++ + " " + DateTime.Now + " " + "Offline");
}
}
}
catch (Exception)
{
}
}
With for
-loop:
using WinSCP;
for (int k = 0; k < 100; k++)
{
using (Session session = new Session())
{
try
{
int i = 0;
// Session Config
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = "",
UserName = "",
Password = "",
SshHostKeyFingerprint = "",
};
session.Open(sessionOptions);
if (session.Opened == true)
{
Console.WriteLine(k + " " + DateTime.Now + " " + "Online");
System.Threading.Thread.Sleep(1000);
session.Close();
}
else if (session.Opened == false)
{
Console.WriteLine("Timeout");
System.Threading.Thread.Sleep(1000);
}
}
catch (Exception)
{
Console.WriteLine(k + " " + DateTime.Now + " " + "Offline");
}
}
}
The
Session
class does not actively check the connection. If you do nothing in the loop, it will never find out the connection was lost. Moreover, if the connection is lost, it won't automatically reconnect.So you have to
Something like this:
Example output: