【问题标题】:Bluetooth connected thread instantly closes socket after connection蓝牙连接线程在连接后立即关闭套接字
【发布时间】:2019-12-11 19:25:03
【问题描述】:

我有一个针对最新类型 Android API (29) 的 Android 应用。用户可以搜索附近的蓝牙设备并连接到它们以发送数据。蓝牙连接是以应用为客户端进行的。

我从 Anroid 的文档中复制了大部分代码并对其进行了更改以满足我的需要。该应用确实会找到设备、正确配对并连接。

问题是,在它连接后,在 Connected 线程的第一个循环中,当它尝试读取传入流时,抛出异常并且套接字断开连接。

我已直接连接到设备的正确 uuid,以测试通过可能的服务器蓝牙 uuid 循环是否会干扰 rfcomsocket。 在尝试读取之前,我尝试在循环中的连接线程中检查mInputStream.available() > 0,但它似乎也在那里引发了异常。

为了测试连接,我激活了我的笔记本电脑蓝牙适配器并将其设置为接收文件(作为服务器)。我曾经在 Xamarin.Android 中有这个应用程序,并且代码曾经以这种方式工作。目前它在 Kotlin 中运行。

下面的代码支持从相应函数调用的 Connect 和 Connected 线程。

fun connect(device: BluetoothDevice, uuids: ArrayList<ParcelUuid>) {
    if (connectionState == STATE_CONNECTING) {
        if (connectThread != null) {
            connectThread?.cancel()
            connectThread = null
        }
    }

    // Cancel any thread currently running a connection
    if (connectedThread != null) {
        connectedThread?.cancel()
        connectedThread = null
    }
    connectThread = ConnectThread(device, this, uuids)
    connectThread?.start()
}


private inner class ConnectThread(
    val device: BluetoothDevice,
    service: BTService,
    val uuids: ArrayList<ParcelUuid>
) : Thread() {

    var socket: BluetoothSocket? = null

    init {
        service.connectionState = STATE_CONNECTING
    }

    override fun run() {
        // Cancel discovery because it otherwise slows down the connection.
        btAdapter?.cancelDiscovery()

        for (uuid in uuids) {
            try {

                val mmSocket: BluetoothSocket? by lazy(LazyThreadSafetyMode.NONE) {
                    device.createRfcommSocketToServiceRecord(uuid.uuid)
                }
                mmSocket?.use { thisSocket ->
                    // Connect to the remote device through the socket. This call blocks
                    // until it succeeds or throws an exception.
                    thisSocket.connect()

                    // The connection attempt succeeded. Perform work associated with
                    // the connection in a separate thread.
                    socket = thisSocket
                    connected(thisSocket)
                }
                break
            } catch (e: IOException) {
                // Close the socket
                cancel()

                // Start the service over to restart listening mode
                Log.e(TAG, "unable to connect() to socket.", e)
            }
        }
    }

    // Closes the client socket and causes the thread to finish.
    fun cancel() {
        try {
            socket?.close()
        } catch (e: IOException) {
            Log.e(TAG, "Could not close the client socket", e)
        }
    }
}


//#####################################                     #####################################
//#####################################----->Connected<-----#####################################
//#####################################                     #####################################

// Start the ConnectedThread to begin managing a Bluetooth connection
fun connected(socket: BluetoothSocket) {
    // Cancel the thread that completed the connection
    if (connectThread != null) {
        connectThread?.cancel()
        connectThread = null
    }

    // Cancel any thread currently running a connection
    if (connectedThread != null) {
        connectedThread?.cancel()
        connectedThread = null
    }

    // Start the thread to manage the connection and perform transmissions
    connectedThread = ConnectedThread(socket)
    connectedThread?.start()

    // Send the name of the connected device back to the UI Activity
    MainActivity.settingsFragment?.activity?.runOnUiThread {
        (MainActivity.settingsFragment as SettingsFragment).btConnected()
    }

}

private inner class ConnectedThread(private val mmSocket: BluetoothSocket) : Thread() {

    private val mmInStream: InputStream = mmSocket.inputStream
    private val mmOutStream: OutputStream = mmSocket.outputStream
    private val mmBuffer: ByteArray = ByteArray(1024) // mmBuffer store for the stream

    init {
        connectionState = STATE_CONNECTED
    }

    override fun run() {
        // Keep listening to the InputStream until an exception occurs.
        while (true) {
            // Read from the InputStream.
            try {
                mmInStream.read(mmBuffer)
            } catch (e: IOException) {
                connectionLost()
                Log.d(TAG, "Input stream was disconnected", e)
                break
            }
            //Do something with stream.
        }
    }

    // Call this from the main activity to send data to the remote device.
    fun write(bytes: ByteArray) {
        try {
            mmOutStream.write(bytes)
        } catch (e: IOException) {
            Log.e(TAG, "Error occurred when sending data", e)
            // Send a failure message back to the activity.

            return
        }
    }

    // Call this method from the main activity to shut down the connection.
    fun cancel() {
        try {
            mmSocket.close()
        } catch (e: IOException) {
            Log.e(TAG, "Could not close the connect socket", e)
        }
    }
}

// Stop all threads.
fun stop() {
    if (connectThread != null) {
        connectThread?.cancel()
        connectThread = null
    }

    if (connectedThread != null) {
        connectedThread?.cancel()
        connectedThread = null
    }

    connectionState = STATE_NONE
}

fun write(bytes: ByteArray) {

    if (connectionState != STATE_CONNECTED) {
        return
    }
    val temp: ConnectedThread? = connectedThread
    temp?.write(bytes)
}

fun connectionLost() {
    MainActivity.settingsFragment?.activity?.runOnUiThread {
        (MainActivity.settingsFragment as SettingsFragment).btLost()
    }
    connectionState = STATE_NONE
}

结果是由于尝试读取时崩溃而导致连接线程的 IO 捕获。我希望它只是在一个活动连接中循环,如果有任何数据被发送给我。

我知道 inputStream 没有保存在任何地方(这是故意的),但我怀疑这是问题所在。

编辑 1: 从连接开始到连接失败(结束)的调试日志...

2019-08-03 18:30:40.583 24961-25088/com.konkarapas.rcs.full.debug W/BluetoothAdapter: getBluetoothService() called with no BluetoothManagerCallback
2019-08-03 18:30:40.776 24961-25088/com.konkarapas.rcs.full.debug D/BluetoothSocket: close() this: android.bluetooth.BluetoothSocket@39f9369, channel: -1, mSocketIS: android.net.LocalSocketImpl$SocketInputStream@611f1ee, mSocketOS: android.net.LocalSocketImpl$SocketOutputStream@96eb68fmSocket: android.net.LocalSocket@15d7d1c impl:android.net.LocalSocketImpl@94fd25 fd:java.io.FileDescriptor@42f3efa, mSocketState: INIT
2019-08-03 18:30:40.780 24961-25088/com.konkarapas.rcs.full.debug E/BluetoothService: unable to connect() to socket.
    java.io.IOException: read failed, socket might closed or timeout, read ret: -1
        at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:762)
        at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:776)
        at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:399)
        at com.konkarapas.rcs.models.BTService$ConnectThread.run(BluetoothService.kt:172)
2019-08-03 18:30:40.782 24961-25088/com.konkarapas.rcs.full.debug W/BluetoothAdapter: getBluetoothService() called with no BluetoothManagerCallback
2019-08-03 18:30:40.934 24961-25088/com.konkarapas.rcs.full.debug D/BluetoothSocket: close() this: android.bluetooth.BluetoothSocket@5534f08, channel: 4, mSocketIS: android.net.LocalSocketImpl$SocketInputStream@ebd46a1, mSocketOS: android.net.LocalSocketImpl$SocketOutputStream@3a250c6mSocket: android.net.LocalSocket@fdce887 impl:android.net.LocalSocketImpl@f5253b4 fd:java.io.FileDescriptor@cc6abdd, mSocketState: CONNECTED
2019-08-03 18:30:40.938 24961-25088/com.konkarapas.rcs.full.debug D/BluetoothSocket: close() this: android.bluetooth.BluetoothSocket@5534f08, channel: 4, mSocketIS: android.net.LocalSocketImpl$SocketInputStream@ebd46a1, mSocketOS: android.net.LocalSocketImpl$SocketOutputStream@3a250c6mSocket: null, mSocketState: CLOSED
2019-08-03 18:30:40.943 24961-25089/com.konkarapas.rcs.full.debug D/BluetoothService: Input stream was disconnected
    java.io.IOException: socket closed
        at android.net.LocalSocketImpl$SocketInputStream.read(LocalSocketImpl.java:104)
        at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:555)
        at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:88)
        at java.io.InputStream.read(InputStream.java:101)
        at com.konkarapas.rcs.models.BTService$ConnectedThread.run(BluetoothService.kt:245)

第一个异常是合乎逻辑的,因为错误的 uuid。第二个例外是问题。

【问题讨论】:

  • 无异常堆栈跟踪?
  • 唯一抛出的异常是 ConnectThread 在尝试连接到设备时引发的。由于试图找到正确的 uuid,这只是一次异常。在当前设备中,uuid 位于数组中的第二个位置 (uuid[1]),因此它必须失败一次。这是处理的。引发的唯一其他异常是在 ConnectedThread 中,这是问题所在。我使用从连接按钮单击到连接失败消息的整个调试日志编辑了上面的问题。

标签: android multithreading sockets kotlin bluetooth


【解决方案1】:

您正在使用mmSocket?.use,它在完成后会自行清理(即关闭连接)如果您将其更改为mmsocket?.let,它不应在完成后自动关闭连接。 (与网络套接字有完全相同的问题,像这样修复它)

【讨论】:

  • 我尝试了您的建议,但没有任何改变。我还尝试从套接字创建中删除惰性包装器,但没有结果。堆栈跟踪是相同的,问题仍然存在。谢谢你的 awnsr :) 编辑:我使用的是 mmSocket?.use 因为这是 Android 文档的推荐! developer.android.com/guide/topics/connectivity/…
  • 好的,经过更多测试,看来 mmSocket?.use 是问题的一部分,但不是唯一的问题。当我确切地知道如何修复它时,我会带着一个答案回来。再次感谢你:)
  • hm... 其他东西正在关闭您的连接,2019-08-03 18:30:40.938 24961-25088/com.konkarapas.rcs.full.debug D/BluetoothSocket: close() this: android.bluetooth.BluetoothSocket@5534f08, channel: 4, mSocketIS: android.net.LocalSocketImpl$SocketInputStream@ebd46a1, mSocketOS: android.net.LocalSocketImpl$SocketOutputStream@3a250c6mSocket: null, mSocketState: CLOSED 行将指示发生这种情况的位置,但我找不到实际记录的部分。跨度>
  • 我不太擅长线程,但我认为关闭其中包含活动套接字的线程可能与它有关。祝你好运!
  • 如您所述,上面的堆栈跟踪表明套接字关闭了两次。一个是 .use,另一个是由于某种原因关闭 Connect 线程时。
【解决方案2】:

所以,在深入研究 Kotlin 和 JVM 并进行大量调试之后,我发现了问题所在。 看来,就像 Java 一样,Kotlin 也是通过引用传递的。

这意味着当您将非原始(任何自定义类)对象传递给函数时,它只是将该对象引用到函数中。这意味着对函数中的对象所做的任何更改,即使在函数退出后,也会对“父对象”进行。

问题:

就我而言,这是两个问题。 @Joozd 提到的第一个问题是mmSocket.use 的使用。它在连接后立即关闭了套接字

第二个问题是connected() 函数。创建它是为了关闭ConnectThread 并仅保留一个ConnectedThread。相反,当它关闭ConnectThread 中的套接字时,它也关闭了传递给ConnectedThread 的套接字。

解决办法:

将mmSocket.use 更改为mmSocket.let 以不自动关闭连接。 并删除了不必要的功能connected(),并在建立连接后立即移动内容。无论如何,空值检查都是在连接开始时在 connect() 函数中完成的。

【讨论】:

  • 出色的答案。我刚刚在这个问题上浪费了 3 个小时。不知道为什么连接会自动关闭。你的回答帮助了我。谢谢你。
猜你喜欢
  • 1970-01-01
  • 2014-03-27
  • 1970-01-01
  • 1970-01-01
  • 2021-06-29
  • 1970-01-01
  • 2016-04-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多