连接到设备时出现异常

Exception when connecting to device

我在连接到我的蓝牙设备 (HC-05) 时遇到问题。 当调用 BluetoothClient.Connect() 时,有时会发生异常 - "An invalid argument was supplied." 或其他。但有时设备会连接(通常是在第一次连接时)! 离开应用程序时是否必须关闭连接?

是的,您应该关闭连接并处理 BluetoothClient。

private InTheHand.Net.Sockets.BluetoothClient BTClient = 
new InTheHand.Net.Sockets.BluetoothClient(); 
private System.Net.Sockets.NetworkStream stream;

//代码某处:

stream = BTClient.GetStream();



public void Disconnect()
    {
            if (BTClient == null )
                return;

            try
            {

                if (BTClient != null)
                {
                    if (stream != null)
                    {
                        stream.ReadTimeout = 500;
                        stream.WriteTimeout = 500;
                        stream.Close();
                    }

                    if(BTClient.Connected)
                        BTClient.Close();
                    BTClient.Dispose();                        
                }


            }
            catch (Exception ex)
            {
                throw ex;
            } 

    }