Kotlin readBytes()永远不会完成

我只是试图通过蓝牙套接字来读写,但是我的readBytes调用没有完成。 我认为这是非常简单的,但也许我只是使用错误types的流或东西。 截至目前我的代码只是发送少量的文字作为字节。 这是占位符代码,将被替换为通过流写入和读取文件的代码。 这是我的接收线程:

class ReceiveThread(val inStream:BufferedInputStream):Thread() { var bytes:ByteArray? = null override fun run() { BluetoothService.log("Begin ${BTS_Constants.THREAD_RECEIVE}") BluetoothService.log("preparing to read data") name = BTS_Constants.THREAD_RECEIVE //here is my new code inStream.use { do{ count++ BluetoothService.log("read loop round $count") byteList.add(it.read() as Byte) }while (it.available()>0) } BluetoothService.log("data read: ${byteList.get(0) as Char}") } } 

这是我的发送主题:

 class SendThread(val outStream:BufferedOutputStream, val file:File? = null):Thread(){ var bytes:ByteArray? = null override fun run() { BluetoothService.log("Begin : ${BTS_Constants.THREAD_SEND}") name = BTS_Constants.THREAD_SEND bytes = "hello testing".toByteArray() try{ outStream.use { it.write(bytes) it.flush() } }catch (ioe:IOException){ } BluetoothService.log("data sent") } } 

数据成功发送,并且到达BluetoothService.log("data sent")调用并显示在运行发送线程的设备的logcat中。 对于运行接收线程的设备记录“正在准备读取数据”消息,但从不记录data read: "$bytes message"data read: "$bytes message"

我如何使这个调用inStream.readBytes()完成?

编辑:我收到新的错误消息:

 11-27 23:45:29.298 16253-16413/com.example.zemcd.fileblue E/AndroidRuntime: FATAL EXCEPTION: RECEIVE Process: com.example.zemcd.fileblue, PID: 16253 java.io.IOException: bt socket closed, read return: -1 at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:588) at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:96) at java.io.BufferedInputStream.fill(BufferedInputStream.java:235) at java.io.BufferedInputStream.read(BufferedInputStream.java:254) at com.example.zemcd.fileblue.ReceiveThread.run(BluetoothService.kt:230) 

如果查看Kotlin扩展函数readBytes源代码,则会看到它在InputStream.read(buffer) > 0时启动循环。 据文件记载 :

此方法阻塞,直到输入数据可用,检测到文件结尾或引发exception。

这个循环的第二次迭代冻结你的程序。 所以不要使用readBytes方法。 刚read(buffer) 。 例如 – https://developer.android.com/guide/topics/connectivity/bluetooth.html#ManagingAConnection

更新:

现在ReceiveThread可以从流接收一条消息。 但是你的蓝牙接口很近 所以你的问题是在设置蓝牙连接和inStream的初始化。 也许你错了发送部分。