This project has moved. For the latest updates, please go here.

Listening for data Stream after Bluetooth Device goes out of Range

Topics: Bluetooth - Microsoft
May 30, 2014 at 4:00 AM
Edited May 30, 2014 at 4:01 AM
Hi everyone,

I am in the process of writing an application that discovers, pairs and connects to specific brands of Barcode Scanners. So far everything is working as expected when the device is in range. However an issue has arisen that I cannot seem to resolve.
When a device is connected then goes out of range and then comes back in range, thousands of blank data streams are retrieved by my application.
Is there an efficient way to handle this kind of event?

Here is a snippet of how I handle the Stream...

public void GetScan()
            if (cli.Connected == true)

                Stream peerStream = cli.GetStream();
                byte[] buf = new byte[50];
                _int readLen = peerStream.Read(buf, 0, buf.Length);_
This method is running on it's own thread and waits at the 3rd line (int readLean...) until data is sent from the barcode scanner. The data retrieved is always blank and it get caught constantly reading blank streams.

I appreciate any help I can get on this one.
May 30, 2014 at 9:34 PM
Edited May 30, 2014 at 9:35 PM

"[For any System.IO.Stream] Read also returns when the ‘end’ of the stream has been reached, returning zero in that case. For NetworkStream ‘end of stream’ occurs when the connection has been closed — when the connection was closed “gracefully”; closure due to error is signalled by an exception." :-)

if (_readLen == 0) throw new EndOfStreamException("Then replace this however you really want to handle end/loss of connection.");
BTW with other protocols (e.g. TCP/IP) you'd get a IOException on loss of connection, but read=0 on the peer closing the connection cleanly.