【问题标题】:Connection refused when trying to connect to bluetooth server尝试连接蓝牙服务器时连接被拒绝
【发布时间】:2016-04-23 12:08:34
【问题描述】:

我正在尝试构建一个简单的蓝牙客户端/服务器,其中我的 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(它找到它并说它已“连接”)并在线搜索更多信息,但找不到任何东西。

【问题讨论】:

    标签: python bluetooth raspberry-pi


    【解决方案1】:

    当你想连接到非监听端口时会发生此错误。

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

    【讨论】:

    • documentation 说:deprecated. bind to port zero instead. 。此外,在请求服务时,它表示它在端口1.在选择不同的端口时,我得到了不同的错误。 span>
    • 又一个模糊文档的例子。明确地占用一个端口确实有效。但是端口 1 不起作用。
    猜你喜欢
    • 1970-01-01
    • 2017-01-28
    • 2019-02-09
    • 2021-07-03
    • 2015-06-17
    • 2011-07-14
    • 1970-01-01
    • 2019-05-06
    相关资源
    最近更新 更多