Categories
.NET Bluetooth Windows

Buffered Streams and the Courtesy Flush

One of the challenges with 32feet.NET is to try to provide as consistent an experience as possible on multiple platforms even though the underlying implementation varies wildly. One such case is with Bluetooth Classic and the stream used to read and write data over an RFCOMM connection.

As it turns out each platform has its own way of implementing these connections, either using Berkeley sockets (Win32 and Linux), BluetoothSocket (Android), ExternalAccessory framework (iOS) or IOBluetooth (macOS). Because there is a level of abstraction even within these native APIs (not including anything 32feet is doing to hide the implementation) what you get when you want to just write to a stream is not at all the same.

One place this becomes clear is when writing an app to talk between multiple platforms e.g. Windows and Android because it soon becomes clear that you’re writing data and not seeing it on the remote device. This is because on Windows the stream is internally buffered and so simply writing data to it doesn’t actually send it over the air to the other device. Either you have to hit a specific buffer level where it will have to send it, or you must call Flush (or FlushAsync) to ensure the buffer is emptied. This doesn’t necessarily mean that you should call flush with each write to the stream, but if you are building a packet containing a chunk of data you probably want to ensure this is flushed so that the receiving device can process it together.

Trial and error shows that the Android side of things doesn’t do this and a write is a write. However, knowing what we know about all the many versions and flavours of Android OS it’s probably best not to assume this is always the case. If the stream has no buffer, or the buffer is already empty then a well placed Flush will not have a measurable impact. Therefore I recommend always adding code to flush data, regardless of what platforms you intend to support so you can ensure it will behave consistently across any platform.

By Peter Foot

Microsoft Windows Development MVP

One reply on “Buffered Streams and the Courtesy Flush”

Comments are closed.