【问题标题】:UWP RfComm - StreamSocketListener.BindServiceNameAsync throws exceptionUWP RfComm - StreamSocketListener.BindServiceNameAsync 抛出异常
【发布时间】:2018-01-10 01:32:08
【问题描述】:

我正在尝试创建一个监听蓝牙串行端口连接的 UWP 应用。当我在应用程序中设置侦听器时(通过单击按钮),我在该行遇到异常:

await socketListener.BindServiceNameAsync( 
      rfcommProvider.ServiceId.ToString(),
      SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);` 

异常消息是: System.ArgumentException: '参数不正确。 'protectionLevel':IP StreamSocketListeners 只允许使用普通套接字。'

代码如下:

private async void btnBluetoothServerClick(object sender, RoutedEventArgs e)
{
   var rfcommProvider = 
   await RfcommServiceProvider.CreateAsync(RfcommServiceId.SerialPort);

   var socketListener = new StreamSocketListener();

   socketListener.ConnectionReceived += OnConnectionReceived;

   await socketListener.BindServiceNameAsync( 
      rfcommProvider.ServiceId.ToString(),
      SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

   rfcommProvider.StartAdvertising(socketListener);
}

protectionLevel参数SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication,改成SocketProtectionLevel.PlainSocket,如异常所示,新的异常信息为:System.Exception: '指定的类是未找到。 (HRESULT 异常:0x8007277D)'.

应用清单文件包括:

<Capabilities>
   <Capability Name="internetClient" />    
   <DeviceCapability Name="bluetooth" />
   <DeviceCapability Name="proximity" />
   <DeviceCapability Name="serialcommunication">
     <Device Id="any">
        <Function Type="name:serialPort" />
     </Device>
   </DeviceCapability>
   <DeviceCapability Name="bluetooth.rfcomm">
      <Device Id="any">        
         <Function Type="name:serialPort" />       
      </Device>
   </DeviceCapability>
   <DeviceCapability Name="wifiControl" /> 
</Capabilities>

似乎这段代码应该根据以下文档工作: https://docs.microsoft.com/en-us/uwp/api/windows.networking.sockets.streamsocketlistener#Windows_Networking_Sockets_StreamSocketListener_BindServiceNameAsync_System_String_Windows_Networking_Sockets_SocketProtectionLevel_Windows_Networking_Connectivity_NetworkAdapter_

我做错了什么?

【问题讨论】:

    标签: bluetooth uwp serial-port listener rfcomm


    【解决方案1】:

    只需更改BindServiceNameAsync方法的参数,

    rfcommProvider.ServiceId.ToString()
    

    rfcommProvider.ServiceId.AsString()
    

    那么你的代码 sn-p 就可以了。

    RfcommServiceIdAsString() 方法会将RfcommServiceId 转换为字符串。ToString 将返回不是BindServiceNameAsync 的正确参数的类型。

    更多详情请参考official sample

    【讨论】:

    • 谢谢!那解决了它。我不敢相信我错过了那个让我一个小时想我疯了的小细节!
    猜你喜欢
    • 1970-01-01
    • 2013-05-24
    • 2019-04-02
    • 2018-12-06
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多