简体   繁体   English

JSch / Java-检测断开服务器的正确方法

[英]JSch/Java - proper way to detect disconnected server

I'm using the Jsch library to execute some commands on a server, using SSH. 我正在使用Jsch库通过SSH在服务器上执行一些命令。 My app should stay connected to the server, until the user manually disconnects it. 我的应用程序应保持与服务器的连接,直到用户手动断开连接为止。 So, I need some way to detect disconnects due to network problems (for example), to allow my app to automatically reconnect. 因此,我需要某种方法来检测由于网络问题引起的断开连接(例如),以允许我的应用自动重新连接。

There is the #isConnected() method. #isConnected()方法。 Can I use it to perform my check? 我可以用它来进行检查吗? I mean, if this method can detect disconnects caused by network problems, or it only changes state, after I call the method #disconnect() ? 我的意思是,如果此方法可以检测到由网络问题引起的断开连接,或者仅在我调用方法#disconnect()之后才更改状态,该方法是否#disconnect()

[edit] It seems that the status of a connection in JSch is only updated if some action occurs over this connection. [edit]似乎只有在此连接上发生某些操作时,JSch中的连接状态才会更新。 So I can't handle network errors this way. 因此,我无法以这种方式处理网络错误。 I can create new thread to monitor my host and port using Socket (for example), but I don't like this workaround. 我可以使用Socket创建新线程来监视主机和端口(例如),但我不喜欢这种解决方法。 It would cause huge battery draining when applied in a backround. 在背景中使用时,会导致大量的电池电量消耗。 It's not acceptable. 不可以

I also need to notify user that server closed the connection and let him to retry. 我还需要通知用户服务器已关闭连接,然后让他重试。

I have gone though the source , it seems that you can use it that way, yes. 我已经看过源代码了 ,看来您可以那样使用它,是的。 I would write a provider class, which provides the Session for your application, and if the connection is lost, it tries to reestablish it after a delay. 我将编写一个提供程序类,为您的应用程序提供Session ,如果连接断开,则它会在延迟后尝试重新建立连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM