Question

I've got Android device acting as a client, the PC is a Bluetooth Server, using Bluecove library

Code snippet from the client:

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());

And the server:

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);

When the osw.close(); at the client is uncommented, the message gets transferred to the server, however, client is then unable to receive the response, IOException with message "socket already closed" is thrown. However, when osw.close(); is commented, both client and server freeze: A. Client hangs on reading server's response of course B. Server hangs on streamConnNotifier.acceptAndOpen();

What should be done to enable two-way communication? Is my code, or PC Bluetoototh stack, or bluecove to blame?

Was it helpful?

Solution

Bluetooth uses buffered output. That means there is a small memory location that contains all of the data you write to the stream. When this memory location gets full, it writes the buffer data to the socket in a packet. When you prematurely close the socket, that buffer gets wiped, and the data is gone.

In order to force the stream to write, try calling flush()

Something else you could do is set the buffer size to be very small, so data always gets written. The performance won't be very good if you do this, though.

Unfortunately, I don't have all of the code I wrote, but there's a base project here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top