StreamSocket: datareader.LoadAsync() closes the connection when no data is available; dataReader.UnconsumedBufferLength is always 0

0

I'm facing with an old known issue related with Bluetooth RFCOMM SPP serial port devices but I couldn't find a reasonable solution/workaround to detect if the DataReader socket is empty without closing the connection.

What I've tried until now:

1) using CancellationTokenSource the underlying streamSocket is closed when is nothing to read. In this case, I need to do a full await streamSocket.ConnectAsync(...).AsTask() and sometimes is generating an exception "Element not found. (Exception from HRESULT: 0x80070490)". why? there is any other solution to detect that the datareader is empty without closing the streamSocket ?

[here is the c# code]

//connect your Windows.Devices.Bluetooth.Rfcomm.RfcommDeviceService 
// see the Bluetooth chat example
[...]
StreamSocket streamSocket = new StreamSocket();  
await streamSocket.ConnectAsync(...); //connect to Bluetooth device

DataReader dataReader = new DataReader(inputStream); // to read from the stream
uint ReadBufferLength = 1024;

// Set InputStreamOptions to complete the asynchronous read operation when one or more bytes is available
dataReader.InputStreamOptions = InputStreamOptions.Partial;

try

{

using (CancellationTokenSource cts = new CancellationTokenSource(timeout))

{

cts.Token.Register(() => { ErrorInfoHandling.SetError("Timeout"); });

Task<uint> loadAsyncTask = dataReader.LoadAsync(ReadBufferLength ).AsTask(cts.Token);

uint bytesRead = await loadAsyncTask;
...

}

}

catch (Exception)
{

 // we will get here, and everything looks fine, but the problem is:

  // The underlying streamSocket is also closed!

  // we can not re-use the streamSocket. Any more calls to LoadAsync results in exceptions (something about the object being not assigned...)

  // we need to do a full   await streamSocket.ConnectAsync(...) sometimes is generating an exception  

// TimeoutExceptionRead:Element not found. (Exception from HRESULT: 0x80070490)

 //   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
  
// at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
 
  //at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
}

2) using dataReader.UnconsumedBufferLength

In this case I do not know why every time UnconsumedBufferLength is 0 even if there is data available on the socket. (also when I run the first scenario and there is data on the socket dataReader.UnconsumedBufferLength is 0). Why dataReader.UnconsumedBufferLength is always 0 even there is data available?

Could someone please give me a hint how to solve this issue?

c#
bluetooth
rfcomm

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0