尝试连接到蓝牙服务器时连接被拒绝

时间:2016-04-23 12:08:34

标签: python bluetooth raspberry-pi

我正在尝试构建一个简单的蓝牙客户端/服务器,其中我的Raspberry Pi是服务器,而我的笔记本电脑是客户端。

这是服务器代码(在我的Raspberry Pi上运行):

#!/usr/bin/python
# -*- coding: utf-8

import wifi, bluetooth

uuid="1e0ca4ea-299d-4335-93eb-27fcfe7fa848"

print "Setting up Bluetooth socket"

try:
  sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
  sock.bind(("", 0))
  sock.listen(1)
except IOError as e:
  print str(e)


print "Registering service"
try:
  bluetooth.advertise_service(sock, "MyService", uuid)

  while True:
    print "Waiting for connection..."  
    client_sock,address = sock.accept()
    print "Accepted connection from {0}".format(address)

    data = client_sock.recv(1024)
    print "Received data: {0}".format(data)

    print "Closing client socket."
    client_sock.close()
except IOError as e:
  print str(e) 

这似乎有效,脚本运行并阻止Waiting for connection...

然后,我的客户代码:

#!/usr/bin/python
# -*- coding: utf-8

import bluetooth, time

mac = "00:15:83:E5:E2:46"
uuid = "1e0ca4ea-299d-4335-93eb-27fcfe7fa848"

service = []
retry = 1
while len(service) == 0:
  print "Looking for service on {0}, try {1}".format(mac, retry)
  service = bluetooth.find_service(address=mac, uuid=uuid)
  retry = retry + 1
  time.sleep(1)

if len(service) == 1: 
  service = service[0]
  print "Service found. Name={0}".format(service["name"])

  print "Connecting to service."

  sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
  try:
    sock.connect((mac, service["port"]))
    print "Connected to service on {0} on port {1}".format(mac, service["port"])
  except bluetooth.btcommon.BluetoothError as e:
    print "Connection failed: {0}".format(e)

elif len(service) == 0:
  print "No service found on mac {0}.".format(mac)
else:
  print "{0} services found for mac/uuid, ignored.".format(len(service))

同样有效,直到我尝试connect()到Raspberry Pi。我收到以下错误:

Connecting to service.
Connection failed: (111, 'Connection refused')

我尝试将笔记本电脑连接到Raspberry Pi(它发现它并说它是#34;已连接")并在线搜索更多信息,但无法找到任何内容。

1 个答案:

答案 0 :(得分:2)

当您想要连接到非侦听端口时,会发生此错误。

你正在监听端口" 0" ..... 将其更改为例如9999,然后客户端必须连接到服务器地址上的该端口