我有 Android 设备作为客户端,PC 是蓝牙服务器,使用 Bluecove 库
来自客户端的代码片段:
btSocket = serverBt.createRfcommSocketToServiceRecord(myUuid);
btAdapter.cancelDiscovery();
btSocket.connect();
InputStream in = btSocket.getInputStream();
OutputStream out = btSocket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(out);
InputStreamReader isr = new InputStreamReader(in);
osw.write(55);
osw.flush();
out.flush();
//osw.close();
logTheEvent("Stuff got written, now waiting for the response.");
int dummy = isr.read();
logTheEvent("Servers response: "+ new Integer(dummy).toString());
和服务器:
StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString, Connector.READ_WRITE );
StreamConnection incomingConnection=streamConnNotifier.acceptAndOpen();
InputStream in = incomingConnection.openInputStream();
OutputStream out = incomingConnection.openOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(out);
InputStreamReader isr = new InputStreamReader(in);
int fromClient = isr.read();
System.out.println("Got from client " + new Integer(fromClient).toString());
osw.write(999);
当osw.close(); 在客户端未注释时,消息被传输到服务器,但是,客户端无法接收响应,抛出带有消息“套接字已关闭”的 IOException。然而,当osw.close(); 已评论,客户端和服务器都冻结: A. 客户端挂起当然读取服务器的响应 B. 服务器挂在 streamConnNotifier.acceptAndOpen();
应该怎么做才能实现双向通信?是我的代码、PC 蓝牙堆栈或 bluecove 造成的吗?