且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android蓝牙IOException:读取失败,套接字可能关闭或超时,读取ret:-1

更新时间:2021-09-21 07:51:44

最后,根本原因是因为无法读取套接字的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