[英]How to detect connection loss in a Apache SocketClient on Android?
I'm making an Android app which opens a telnet connection using Apache's TelnetClient
.我正在制作一个 Android 应用程序,它使用 Apache 的
TelnetClient
打开一个 telnet 连接。 For this, I created a Runnable
which will keep reading in processInput()
forever.为此,我创建了一个
Runnable
,它将永远在processInput()
读取。 I check with isConnected()
if the socket is still connected, and if not, I return from the runnable and call onDisconnected()
on the listeners.我用
isConnected()
检查套接字是否仍然连接,如果没有,我从 runnable 返回并在侦听器上调用onDisconnected()
。 However, this last method is never called, even when I turn of Wi-Fi.但是,即使我关闭 Wi-Fi,也永远不会调用最后一个方法。
I could check the Wi-Fi state, but that does not capture cases when the server hangs up or when the connection is lost for other reasons.我可以检查 Wi-Fi 状态,但这并不能捕获服务器挂断或由于其他原因丢失连接的情况。 How do I detect when the connection is closed?
如何检测连接何时关闭?
private class ClientThread implements Runnable {
@Override
public void run() {
while (true) {
if (!client.isConnected()) {
for (NewRecordListener listener : listeners)
listener.onDisconnected();
try { client.disconnect(); } catch (IOException e) {}
return;
}
try {
processInput();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
"I check with isConnected() if the socket is still connected" “如果套接字仍然连接,我检查 isConnected()”
You cannot:你不能:
"Returns: true if the socket successfuly connected to a server"
“返回:如果套接字成功连接到服务器,则为真”
does not necessarily mean it will be false as soon as the connection breaks.并不一定意味着一旦连接中断它就会是假的。
"How do I detect when the connection is closed" “如何检测连接何时关闭”
Sidenote:边注:
I am tempted to say that this doc :我很想说这个文档:
Returns true if the client is currently connected to a server.
如果客户端当前连接到服务器,则返回 true。
is plain wrong.完全错误。 The docs of the Java 6 Socket.isConnected to which this method delegates to does not say that:
此方法委托给的 Java 6 Socket.isConnected的文档没有说:
Returns: true if the socket successfuly connected to a server
返回: 如果套接字成功连接到服务器,则为 true
Typical behavior of the Java TCP Socket implementations of isConnected is that they return true when the Socket has been successfully connected - and keep on doing so . isConnected 的 Java TCP Socket 实现的典型行为是当 Socket 已成功连接时它们返回 true -并继续这样做。
See also https://docs.oracle.com/javase/8/docs/api/java/net/Socket.html#isConnected-- :另请参阅https://docs.oracle.com/javase/8/docs/api/java/net/Socket.html#isConnected-- :
Note: Closing a socket doesn't clear its connection state, which means this method will return true for a closed socket ... "
注意:关闭套接字不会清除其连接状态,这意味着对于关闭的套接字,此方法将返回 true ......“
That's for Java 8, though.不过,那是针对 Java 8 的。 I don't know if they just added that Note or if behavior changed, but I suspect the first.
我不知道他们是刚刚添加了那个 Note 还是行为发生了变化,但我怀疑是第一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.