Python蓝牙通信报错:AttributeError: module 'socket' has no attribute 'AF_BLUETOOTH'
AttributeError: module 'socket' has no attribute 'AF_BLUETOOTH' on Windows 10 Hey there! Let's break down why you're hitting this error and how to fix it.
Why This Happens
The Python socket module's documentation mentions AF_BLUETOOTH and related Bluetooth constants, but these aren't fully supported on Windows—especially not in older Python versions like 3.6.4. The cross-platform docs cover features that work smoothly on Linux/macOS, but Windows has historically had limited native Bluetooth socket support in Python's standard library.
Solutions to Try
1. Upgrade Your Python Version (First Step!)
Python 3.6.x is pretty outdated (it reached end-of-life in 2021) and lacks many modern Bluetooth improvements added in later versions. Upgrading to Python 3.8 or newer will give you better (though still limited) native Bluetooth support on Windows. Even with a newer version, you might still run into quirks with Windows' Bluetooth stack, so a dedicated library is often better.
2. Use a Third-Party Bluetooth Library (Recommended)
For reliable Bluetooth communication on Windows, the best bet is to use PyBluez—a popular Python library built specifically for Bluetooth interactions. Here's how to set it up:
First, install PyBluez via pip:
pip install pybluez
Then, modify your code to use PyBluez's API instead of the native socket module. Here's an adapted version of your server code:
import bluetooth hostMACAddress = 'your_device_mac_address' port = 3 backlog = 1 size = 1024 server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) server_sock.bind((hostMACAddress, port)) server_sock.listen(backlog) try: client_sock, client_info = server_sock.accept() print(f"Connected to {client_info}") while True: data = client_sock.recv(size) if data: print(f"Received: {data.decode('utf-8')}") client_sock.send(data) except Exception as e: print(f"Error occurred: {e}") print("Closing sockets") client_sock.close() server_sock.close()
3. Double-Check Windows Bluetooth Setup
- Make sure your Bluetooth device is paired with your Windows 10 machine.
- Ensure your PC's Bluetooth is turned on, and try running your Python script as Administrator if you hit access permission issues.
内容的提问来源于stack exchange,提问作者to_matih

