如何在 Android 上检测 Apache SocketClient 中的连接丢失?

How to detect connection loss in a Apache SocketClient on Android?

我正在制作一个 Android 应用程序,它使用 Apache 的 TelnetClient 打开一个 telnet 连接。为此,我创建了一个 Runnable 它将永远在 processInput() 中读取。我用 isConnected() 检查套接字是否仍然连接,如果没有,我从 runnable 中 return 并在监听器上调用 onDisconnected()。但是,即使我关闭 Wi-Fi,也不会调用最后一个方法。

我可以检查 Wi-Fi 状态,但无法捕获服务器挂起或连接因其他原因丢失的情况。如何检测连接何时关闭?

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"

你不能:

"Returns: true if the socket successfuly connected to a server"

并不一定意味着一旦连接断开就为false

"How do I detect when the connection is closed"

  • 在 non-graceful 连接中止时,通常只有在尝试写入时才有机会获得 IOException。
  • 您可能需要定期使用:AreYouThere

旁注:

我很想说这个 doc:

Returns true if the client is currently connected to a server.

完全错误。此方法委托给 Java 6 Socket.isConnected 的文档没有说明:

Returns: true if the socket successfuly connected to a server

isConnected 的 Java TCP 套接字实现的典型行为是当套接字已成功连接时 return 为真 - 并继续这样做.

另见 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 ... "

不过,那是 Java 8 的。我不知道他们是刚刚添加了那个注释还是行为发生了变化,但我怀疑是第一个。