1

我有 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 造成的吗?

4

1 回答 1

2

蓝牙使用缓冲输出。这意味着有一个小的内存位置包含您写入流的所有数据。当此内存位置已满时,它将缓冲区数据以数据包的形式写入套接字。当您过早关闭套接字时,该缓冲区会被擦除,数据也会消失。

为了强制流写入,请尝试调用flush()

您可以做的其他事情是将缓冲区大小设置为非常小,以便始终写入数据。但是,如果您这样做,性能将不会很好。

不幸的是,我没有我写的所有代码,但是这里有一个基础项目

于 2012-10-15T21:37:47.683 回答