StreamSocket:当没有可用数据时,datareader.LoadAsync将关闭连接; dataReader.UnconsumedBufferLength始终为0

问题描述

我正面临着与蓝牙RFCOMM SPP串行端口设备有关的老问题,但是我找不到一种合理的解决方案/解决方法来检测DataReader套接字是否为空而不关闭连接。

到目前为止我一直尝试的操作:

1),使用CancellationTokenSource可以在无需读取任何内容时关闭基础streamSocket。 在这种情况下,我需要完全等待streamSocket.ConnectAsync(...)。AsTask(),有时会生成异常“找不到元素。(来自HRESULT的异常:0x80070490)。”为什么?还有其他解决方案可以在不关闭streamSocket的情况下检测到数据读取器为空?

[这是c#代码]

//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)使用dataReader.UnconsumedBufferLength

在这种情况下,即使套接字上有可用数据,我也不知道为什么每次UnconsumedBufferLength都为0。 (同样,当我运行第一个方案时,套接字上的数据dataReader.UnconsumedBufferLength为0)。即使有可用数据,为什么dataReader.UnconsumedBufferLength始终为0?

有人可以给我提示如何解决这个问题吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...