代码如下:
from bluetooth import *
import sys
if sys.version < '3':
input = raw_input
addr = None
if len(sys.argv) < 2:
print("no device specified. Searching all nearby bluetooth devices for")
print("the SampleServer service")
else:
addr = sys.argv[1]
print("Searching for SampleServer on %s" % addr)
# search for the SampleServer service
addr = "CC:79:4A:4B:35:85"
service_matches = find_service( address = addr )
if len(service_matches) == 0:
print("couldn't find the SampleServer service =(")
sys.exit(0)
first_match = service_matches[0]
port = first_match["port"]
name = first_match["name"]
host = first_match["host"]
print("connecting to \"%s\" at Address - %s on Port %d" % (name, host, port))
# Create the client socket
sock=BluetoothSocket( RFCOMM )
sock.connect((host, port))
print("connected. type stuff")
while True:
data = input()
if len(data) == 0: break
sock.send(data)
sock.close()
运行时错误抛出如下:
no device specified. Searching all nearby bluetooth devices for
the SampleServer service
connecting to "None" at Address - CC:79:4A:4B:35:85 on Port 31
Traceback (most recent call last):
File "T_C_1.py", line 40, in <module>
sock.connect((host, port))
File "C:\Python 3.5\lib\site-packages\bluetooth\msbt.py", line 72, in connect
bt.connect (self._sockfd, addr, port)
OSError: The requested address is not valid in its context.
我无法弄清楚原因。有些网站告诉我,我的主机地址需要在本地机器上....这段代码驻留在我的WIndows机器上,试图通过蓝牙连接到Android手机。我不知道为什么/如何...帮助表示赞赏!
我在Windows上使用PyBluez遇到了同样的错误,因为我在收到绑定错误后不得不离开我的Mac环境。我发现当你绑定到一个外部IP地址或你的系统不知道的地址(例如公共IP之外)时会出现问题。尝试使用''的addr在PyBluez中创建服务器并尝试连接到该服务器。如果不起作用,我们可以从那里进一步诊断您的问题。很抱歉它不是一个可靠的答案,我是StackOverflow的新手,我无法评论,但我想提供一些帮助。