Android蓝牙IOException:读取失败,套接字可能关闭或超时,读取ret:-1 [英] Android bluetooth IOException: read failed, socket might closed or timeout, read ret: -1

查看:199
本文介绍了Android蓝牙IOException:读取失败,套接字可能关闭或超时,读取ret:-1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Android蓝牙API中连接客户端套接字时遇到问题. 我已经阅读了以下文章:这个这个 根据这些帖子,我使代码如下所示,但仍然无法正常工作:

I have a problem with connecting my client socket in the Android bluetooth API. I already read these posts: this one, this one, this one and this one According to these posts I made my code like the following but it still not work:

class MainActivity : AppCompatActivity()
{
    private val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
    private var connectThread: ConnectThread? = null

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if (bluetoothAdapter != null)
        {
            if (!bluetoothAdapter.isEnabled)
                bluetoothAdapter.enable()

            val devices = bluetoothAdapter.bondedDevices.toTypedArray()


            if (devices.isNotEmpty())
            {
                connectThread = ConnectThread(devices[0])
                connectThread!!.run()
            }
        }
        else
            Log.i("BluetoothTest", "No bluetooth supported")
    }

    override fun onDestroy()
    {
        super.onDestroy()

        connectThread!!.cancel()
    }

    private inner class ConnectThread(device: BluetoothDevice) : Thread()
    {
        //private val socket = device.createRfcommSocketToServiceRecord(UUID.fromString ("00001101-0000-1000-8000-00805F9B34FB"))
        private val socket = device.javaClass.getMethod("createRfcommSocket", (Int::class
            .javaPrimitiveType)).invoke(device, 2) as BluetoothSocket

        override fun run()
        {
            bluetoothAdapter.cancelDiscovery()
            socket.connect()
        }

        fun cancel()
        {
            socket.close()
        }

    }
}

这是socket.connect()上带有返回错误的日志:

Here is the logs with the returned error that comes on socket.connect():

--------- beginning of crash
05-15 15:59:19.553 24176-24176/com.bluetoothtest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.bluetoothtest, PID: 24176
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bluetoothtest/com.bluetoothtest.MainActivity}: java.io.IOException: read failed, socket might closed or timeout, read ret: -1
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
    at android.app.ActivityThread.-wrap11(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6494)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
 Caused by: java.io.IOException: read failed, socket might closed or timeout, read ret: -1
    at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:685)
    at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:697)
    at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:374)
    at com.bluetoothtest.MainActivity.onCreate(MainActivity.kt:36)
    at android.app.Activity.performCreate(Activity.java:6999)
    at android.app.Activity.performCreate(Activity.java:6990)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)

由于套接字的端口值,似乎在Android 4.3之后出现了问题 我在Android 7.1和8.1上 有人知道如何在Android上使蓝牙正常工作吗?

It seems that the problem appeared after Android 4.3 because of the port value of the socket I am on Android 7.1 and 8.1 Does someone knows how to make bluetooth work on Android ?

推荐答案

最后,根本原因是因为无法读取套接字的inputStream.这是因为服务器端没有打开的套接字具有相同的UUID .

Finally, the root cause was because the socket's inputStream couldn't be read. That's because there was no open socket with the same UUID on the server side.

请参见因此,要解决此问题,我们需要在另一侧使用具有相同UUID的侦听套接字,对我而言,这是python中的树莓派:

So to fix the problem we need a listening socket with the same UUID on the other side, for me it was a raspberry in python:

from bluetooth import *

server_sock=BluetoothSocket( RFCOMM )
server_sock.bind(("",PORT_ANY))
server_sock.listen(1)

port = server_sock.getsockname()[1]

uuid = "YOUR UUID"

advertise_service( server_sock, "SampleServer", service_id = uuid, service_classes = [ uuid, SERIAL_PORT_CLASS ], profiles = [ SERIAL_PORT_PROFILE ])

print("Waiting for connection on RFCOMM channel %d" % port)

client_sock, client_info = server_sock.accept()
print("Accepted connection from ", client_info)

try:
    while True:
        data = client_sock.recv(1024)
        if len(data) == 0: break
        print("received [%s]" % data)
except IOError:
    pass

print("disconnected")

client_sock.close()
server_sock.close()
print("all done")

来自 https://github.com/karulis/pybluez/blob/master/examples/simple/rfcomm-server.py

这篇关于Android蓝牙IOException:读取失败,套接字可能关闭或超时,读取ret:-1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆