【发布时间】:2020-07-28 05:08:55
【问题描述】:
我正在编写一个应该通过蓝牙发送文件的 android 应用程序。现在我只是想发送文本。发送设备似乎可以正确发送,而接收设备正在接收来自其他设备的连接。接收器能够从侦听服务器套接字中获取一个套接字,并从中获取一个输入流。我的问题是它无法从输入流中读取。真正让我困惑的部分是我得到的异常表明相关的套接字已关闭,但是 Socket.isConnected() 在尝试读取之前和发生异常之后都返回 true。这怎么可能?这段代码怎么能:
class ReceiveThread(val socket: BluetoothSocket):Thread() {
var count:Int = 0
var bytes:Int = 0
val buffer:ByteArray = ByteArray(1024)
val byteList = mutableListOf<Byte>()
val inStream:InputStream
init {
inStream = socket.inputStream
}
override fun run() {
BluetoothService.log("Begin ${BTS_Constants.THREAD_RECEIVE}")
BluetoothService.log("preparing to read data (socket connected): ${socket.isConnected}")
name = BTS_Constants.THREAD_RECEIVE
try {
bytes = inStream.read(buffer)
}catch (e:Exception){
BluetoothService.log("error reading from stream (socket connected):${socket.isConnected}", e)
BluetoothService.state = BTS_Constants.STATE_NONE
}
if (byteList.size>0) BluetoothService.log("data read: ${byteList.get(0) as Char}") else BluetoothService.log("failed to get")
}
fun cancel() = inStream.close()
}
导致此日志消息:
11-28 23:23:33.958 25325-25534/com.example.zemcd.fileblue D/BluetoothService: Begin RECEIVE
11-28 23:23:33.958 25325-25534/com.example.zemcd.fileblue D/BluetoothService: preparing to read data (socket connected): true
11-28 23:23:34.035 25325-25534/com.example.zemcd.fileblue E/BluetoothService: error reading from stream (socket connected): true
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.InputStream.read(InputStream.java:101)
at com.example.zemcd.fileblue.ReceiveThread.run(BluetoothService.kt:263)
11-28 23:23:34.035 25325-25534/com.example.zemcd.fileblue D/BluetoothService: failed to get
如果套接字已关闭,为什么返回 true?如何追踪我的套接字关闭的位置?请帮助我理解这一点。
【问题讨论】:
标签: android sockets bluetooth kotlin