我正在尝试建立Android和IOT (英特尔伽利略)设备之间的蓝牙通信。
IOT端的代码(我将它作为客户端),它将发送数据到android,但这里的一个端口号是硬编码的。这是用python编写的。
def record_transmit_to_subscriber(self, subscriber, message):
server_addr = subscriber
port = 6
client_socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
try:
client_socket.connect((server_addr, port))
client_socket.send(message)
client_socket.close()
return True
except Exception as e:
print "Unable to make connection with subscriber", subscriber
return False现在到了android (服务器)端:
private static UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
try {
BluetoothServerSocket tmp = null;
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
try {
// MY_UUID is the applications UUID string, also used by the client code
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) {
GlobalUtils.writeLogFile("Error in BLE Listening " + e.getMessage());
}
mmServerSocket = tmp;
} catch (Exception e){
GlobalUtils.writeLogFile("Exception in Accept Thread " + e.getMessage());
}我确实认为这段代码中存在一些问题,在客户端它使用端口号,而在服务器端它使用uuid。有没有人可以纠正一下如何修改此代码以使连接工作。
发布于 2016-11-02 19:12:13
你似乎忘了创建套接字和流:
try {
BluetoothDevice bluetoothDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("<MAC_address_of_your_device>");
mSocket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(MY_UUID);
mSocket.connect();
} catch (IOException e) {
Log.e(TAG, "Fail connect");
}
// Get the input and output streams for BT socket
try {
inStream = mSocket.getInputStream();
outStream = mSocket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "Fail to open socket streams");
}然后,您可以创建用于从inStream读取数据的Thread (例如,inStream.read(<data_buffer>); )和用于将数据写入outStream的Thread (例如,outStream.write(<data_buffer>); outStream.flush();)。
https://stackoverflow.com/questions/40378240
复制相似问题