You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中Bluetooth套接字无法正常关闭问题排查

Python蓝牙套接字重复关闭问题的修复

你的代码核心问题在于close方法:调用sock.close()后,没有将self.sock重置为None。即使套接字已经关闭,self.sock仍然指向那个已关闭的套接字对象,导致后续调用close时,if self.sock is not None的判断依然为真,所以会重复打印“Connection closed.”而不是预期的“No socket to close.”

修改后的代码

只需要在close方法中关闭套接字后,添加self.sock = None即可:

import bluetooth
import time

class BluetoothHandler:
    def __init__(self):
        self.addr = "12:13:14:04:26:23"
        self.sock = None
        
    def connect(self):
        try:
            if self.sock is None:
                self.sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
                self.sock.connect((self.addr, 1))
                print(f"Connected to {self.addr}")

        except bluetooth.btcommon.BluetoothError as e:
            if "Connection refused" in str(e):
                print("Connection Refused. Check if the device is discoverable and connectable.")
            else:
                print(f"Error: {e}")

    def close(self):
        try:
            if self.sock is not None:
                self.sock.close()
                self.sock = None  # 关键:重置为None
                print("Connection closed.")
            else:
                print("No socket to close.")

        except bluetooth.btcommon.BluetoothError as e:
            print(f"Error during close: {e}")
    


handler = BluetoothHandler()

try:
    while True:
        handler.connect()
        time.sleep(5)
        handler.close()
        time.sleep(5)
        handler.close()
        time.sleep(5)
    
except KeyboardInterrupt:
    pass

finally:
    print("over")

修复后输出

修改后运行代码,会得到你预期的输出:

dietpi@rpi:/opt/dev/project$ sudo python3 test.py 
Connected to 12:13:14:04:26:23
Connection closed.
No socket to close.
No socket to close.
...

补充说明:主循环里连续两次调用close,第一次关闭后self.sock变为None,第二次调用就会触发“No socket to close.”的提示,完全符合你的预期逻辑。

内容的提问来源于stack exchange,提问作者fluffypuffy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 16:15:37