蓝牙socket读取数据需读多次才读全
今天上班解决了一个问题:android程序通过蓝牙socket读取数据时,需要读多次才能把完整的响应APDU读全。当前用的方法来自android示例程序:
<!--EndFragment-->public void run() { Log.i(TAG, "BEGIN mConnectedThread"); byte[] buffer = new byte[1024]; int bytes; // Keep listening to the InputStream while connected while (true) { try { // Read from the InputStream Log.i(TAG, "Read from the InputStream..."); bytes = mmInStream.read(buffer); Log.i(TAG, "Read from the InputStream, length is "+bytes); // Send the obtained bytes to the UI Activity mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer) .sendToTarget(); } catch (IOException e) { Log.e(TAG, "disconnected", e); connectionLost(); break; } } }
响应APDU是
02001580FFFFFFFF00A4040010D15600010180038000000001000000006A03,
接收三次,每次的结果都不一样:
(1)02001580FFFFFFFF00A4040010D1560001018003 8000000001000000006A 03
(2)02 001580FFFFFFFF00A4040010D15600010180038000000001000000006A 03
(3)02001580FFFFFFFF00A4040010D15600010180038000000001000000006A 03
修改示例代码:响应APDU是可以解析的,第3个字节的值加上10就等于响应APDU的长度,其中10是前缀和后缀的长度之和。
public void run() { Log.i(TAG, "BEGIN mConnectedThread"); byte[] buffer = new byte[1024]; // int bytes; int len = 0; int i = 0; // Keep listening to the InputStream while connected while (true) { try { // Read from the InputStream Log.i(TAG, "Read from the InputStream..."); // bytes = mmInStream.read(buffer); buffer[i++] = (byte) mmInStream.read(); if (i == 3) { len = buffer[2] + 10; } Log.i(TAG, "Read from the InputStream, data is " + buffer[i - 1]); if (i == len) { // Send the obtained bytes to the UI Activity mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, len, -1, buffer).sendToTarget(); len = 0; i = 0; } } catch (IOException e) { Log.e(TAG, "disconnected", e); connectionLost(); break; } } }
相关推荐
yangkang 2020-11-09
lbyd0 2020-11-17
sushuanglei 2020-11-12
85477104 2020-11-17
KANSYOUKYOU 2020-11-16
wushengyong 2020-10-28
lizhengjava 2020-11-13
星月情缘 2020-11-13
huangxiaoyun00 2020-11-13
luyong0 2020-11-08
腾讯soso团队 2020-11-06
Apsaravod 2020-11-05
PeterChangyb 2020-11-05
gaobudong 2020-11-04
wwwjun 2020-11-02
gyunwh 2020-11-02
EchoYY 2020-10-31
dingyahui 2020-10-30