3

我正在尝试启动并运行蓝牙套接字连接,但由于某种原因,我的客户端无法连接。

更准确地说,当我尝试连接到流时出现异常: 连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立连接失败,因为连接的主机没有响应。

我在网上找到的所有示例都没有真正解决我的问题,我目前不确定问题出在哪里。扫描和配对工作正常 - 我看到有问题的蓝牙设备已成功配对。

我尝试通过首先设置客户端进行连接,然后调用连接

客户端蓝牙名称、地址和pin是已知的:

    public bool SetClient(String clientName, String btAddress, String pin)
    {
        bool retVal = false;
        m_remoteBluetoothClient = new BluetoothDeviceInfo(BluetoothAddress.Parse(btAddress));
        m_localBluetoothClient.SetPin(pin);
        if (m_remoteBluetoothClient.Authenticated)
        {
            //m_localBluetoothClient.Authenticate = true;
            retVal = true;
        }
        else
        {
            if (BluetoothSecurity.PairRequest(m_remoteBluetoothClient.DeviceAddress, pin))
            {
                retVal = true;
            }
        }
        return retVal;
    }

然后是异步连接:

    private void ClientConnectThread()
    {
        m_localBluetoothClient.BeginConnect(m_remoteBluetoothClient.DeviceAddress, BluetoothService.SerialPort, Connect, m_localBluetoothClient);
    }

    private void Connect(IAsyncResult result)
    {
        if (result.IsCompleted)
        {
            m_localBluetoothClient.EndConnect(result);
            mBtStream = m_localBluetoothClient.GetStream();
        }
    }

本地 m_localBluetoothEndpoint 和 m_localBluetoothClient 是这样创建的,尽管 Endpoint 或多或少是新的(在我使用不带参数的 BluetoothCLient 之前):

        m_localBluetoothEndpoint = new BluetoothEndPoint(BluetoothRadio.PrimaryRadio.LocalAddress, BluetoothService.SerialPort);
        m_localBluetoothClient = new BluetoothClient(m_localBluetoothEndpoint);

我还尝试使用侦听器,以防远程设备想要连接但从未调用过回调:

    public void SetupListener()
    {
        var listener = new BluetoothListener(BluetoothService.SerialPort);
        listener.Start();
        listener.BeginAcceptBluetoothClient(this.BluetoothListenerAcceptClientCallbackTwo, listener);

    }

谁能告诉我上面的连接方法是否有问题,以及如何弄清楚为什么会出现上述异常?

这里抛出异常:

    m_localBluetoothClient.EndConnect(result);

我也不明白的一件事是,对 remoteCLient 的 SupportedServices 调用返回了 0 个 guid - 所以设备没有列出任何蓝牙服务。

    m_remoteBluetoothClient.InstalledServices()

谢谢

4

0 回答 0