如何在不关闭基础套接字的情况下取消LoadAsync()?

时间:2019-09-27 19:09:56

标签: c# xamarin uwp bluetooth rfcomm

我有一个应用程序,可通过蓝牙上的rfcomm与某些硬件进行通信。我的应用程序可在Android上运行,并且正在使UWP正常运行。这是我在UWP代码中设置流读取器/写入器的方式:

var btDevice = await BluetoothDevice.FromIdAsync(devId);

var services = await btDevice.GetRfcommServicesAsync();

if (services.Services.Count > 0)
{
    // We only have one service so use the first one...
    var service = services.Services[0];
    // Create a stream...
    _bluetoothStream = new StreamSocket();
    await _bluetoothStream.ConnectAsync(service.ConnectionHostName, service.ConnectionServiceName);

    _dataReader = new DataReader(_bluetoothStream.InputStream);
    _dataWriter = new DataWriter(_bluetoothStream.OutputStream);

    _dataReader.InputStreamOptions = InputStreamOptions.Partial;

我的硬件仅在应用程序发送数据后才将数据发送到我的应用程序,因此我已经设置了发送/接收机制。除了我的设备正在重新启动(但蓝牙连接仍处于活动状态)且无法发送响应的特定用例之外,一切工作都很好。在这种情况下,我的上层代码已设置为尝试重试,但是当接收超时时,蓝牙连接将关闭。

_dataWriter.WriteBytes(comm.TransmitData);

Task<UInt32> writeAysncTask = _dataWriter.StoreAsync().AsTask();

UInt32 bytesWritten = await writeAysncTask;
:
try
{
    using (var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(comm.TimeoutMs))) // _receiveTimeoutMs)))
    {
        // When this times out, exception gets thrown and socket is closed
        // How do I prevent the socket from closing so I can do a retry???
        var loadTask = _dataReader.LoadAsync(comm.ReceiveCount).AsTask(cts.Token);

        bytesRead = await loadTask;

        if (bytesRead > 0)
        {
            rxData = new byte[bytesRead];
            _dataReader.ReadBytes(rxData);
        }
        else
        {
            System.Diagnostics.Debug.WriteLine("Received 0!");
        }
    }
}
catch (Exception ex)
{
    // The bluetooth connection is closed automatically if the
    // caancellationToken fires...In my case, I need the connection
    // to stay open...How do I achieve this???


    // Update: When this code is executed with _dataReader/Writer
    // that was created with SerialDevice class (see below), the
    // timeout exception does not cause the Serial connection to
    // close so my calling code can then issue a retry.
    System.Diagnostics.Debug.WriteLine(ex.Message) ;
}

更新:应该注意的是,当我对从SerialDevice创建的流使用完全相同的代码时,一切都会按我的预期进行……当接收超时时,套接字未关闭。似乎我在UWP的蓝牙实施中遇到了挑战。啊。这是我使用SerialDevice类创建_dataReader / _dataWriter的方法:

_serialDevice = await SerialDevice.FromIdAsync(devId);
// Configure the port
_serialDevice.BaudRate = _baudrate;
_serialDevice.Parity = SerialParity.None;
_serialDevice.DataBits = 8;
_serialDevice.StopBits = SerialStopBitCount.One;

_dataReader = new DataReader(_serialDevice.InputStream);
_dataWriter = new DataWriter(_serialDevice.OutputStream);

1 个答案:

答案 0 :(得分:0)

我已经解决了我所面临的问题。不幸的是,我不能对SerialDevice和BluetoothDevice使用相同的代码。我不得不说,取消令牌超时时,蓝牙套接字被关闭真的很臭。如果不关闭,该代码将更加整洁!应该由我决定是否应关闭插座吗?现在我被困住了:

    using (var cts = new CancellationTokenSource())
    {
        Task.Run(async () =>
        {
            try
            {
                await Task.Delay((int)comm.TimeoutMs, cts.Token);

                System.Diagnostics.Debug.WriteLine("Canceling async read");
                // If we make it this far, then the read as failed...cancel the async io
                // which will cause the bytesRead below to be 0.
                await _bluetoothStream.CancelIOAsync();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }, cts.Token);

        var loadTask = _dataReader.LoadAsync(comm.ReceiveCount).AsTask();

        bytesRead = await loadTask;

        if (bytesRead > 0)
        {
            // SIgnal the delay task to cancel...
            cts.Cancel(true);
            if (bytesRead > comm.ReceiveCount)
                System.Diagnostics.Debug.WriteLine("Received too much!!");

            rxData = new byte[bytesRead];
            _dataReader.ReadBytes(rxData);
        }
        else
        {
            System.Diagnostics.Debug.WriteLine("Received 0!");
        }
    }

实施此操作后,我确实注意到,在将BT设备配对后,Windows在以下查询中将其作为SerialDevice返回:

string aqs = SerialDevice.GetDeviceSelector();
DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(aqs);
// My bluetooth device is included in the 'devices' collection

因此,如果我以串行设备连接到它,我想我根本不需要解决。哦,希望这篇文章能对其他人有所帮助。