sshj icon indicating copy to clipboard operation
sshj copied to clipboard

Best strategy to detect that the connection is down?

Open cliviu opened this issue 8 months ago • 4 comments

Hi,

it looks like the method SSHClient.isConnected() will not detect that the server is down after an initial connection is established and afterward the server is shut down.

I have tried even to call SftpClient.ls("/") and surprisingly I get an answer even if the server is not running.

I have also set the timeout to a lower value but still no improvement 
sftpClient.getSFTPEngine().setTimeoutMs(3000);

What is the best approach to recognize when the connection is down?

Thank you!

cliviu avatar Mar 17 '25 11:03 cliviu

Look at my solution. It works well for me.

	public boolean checkConnection(final boolean reconnect) throws IOException {
		try {
			log.debug("[checkConnection] Check connection '" + this.getHostname() + ":" + ssh.getLocalPort() + " Port: "
					+ this.getPort());
			this.ssh.getTransport().write(new SSHPacket(Message.IGNORE));
		} catch (final TransportException e) {
			e.printStackTrace();
			if (reconnect) {
				try {
					this.connect();
					return true;
				} catch (InterruptedException ie) {
					throw new IOException("Interrupted");
				}
			}
			this.log.trace("[] Exception " + StackTrace.getStackTrace(e));
			return false;
		}
		return true;
	}

araneolus avatar May 14 '25 08:05 araneolus

That's actually a pretty nice solution for adding to the lib... I'll incorporate that in a method! Thanks for sharing

hierynomus avatar May 14 '25 09:05 hierynomus

Look at my solution. It works well for me.

Thank you so much

cliviu avatar May 14 '25 09:05 cliviu

I have tested it, and it still does not recognize that the server is down. My workaround is to try to open a new connection to find out if the server is running and then immediately close it.

cliviu avatar May 14 '25 13:05 cliviu