客戶端實現藍牙接收(C#)


  在實現藍牙接收時,網上的資料很多,使用起來也很簡單,但是我覺得還是有必要把這些知識總結下來。藍牙開發需要用到一個第三方的庫InTheHand.Net.Personal.dll,其中關鍵的兩個類是 BluetoothClient 和 BluetoothListener,首先開啟一個子線程來不斷的接收數據,使用很簡單,直接上代碼:

using InTheHand.Net.Sockets;
using System.Threading;

   public MainWindow()
        {
            InitializeComponent();
     listenThread = new Thread(ReceiveData);
            listenThread.Start();
        }

        private void ReceiveData()        
    {
             try
            {   
                 Guid mGUID = Guid.Parse("00001101-0000-1000-8000-00805F9B34FB");
                 bluetoothListener = new BluetoothListener(mGUID);                
          bluetoothListener.Start();                
      bluetoothClient = bluetoothListener.AcceptBluetoothClient();                
         isConnected = true;            
     }            
     catch (Exception)            
     {
       isConnected = false;                  
     }            

         while (isConnected)            
    {                
      string receive = string.Empty; 
      if (bluetoothClient == null)                    
      {                        
         break;
      }                                          
       try                    
      {                        
         peerStream = bluetoothClient.GetStream();   
                        byte[] buffer = new byte[6];
           peerStream.Read(buffer, 0, 6);
         receive = Encoding.UTF8.GetString(buffer).ToString();
      }                        
      catch (System.Exception)                    
      {                                         
      }
      Thread.Sleep(100);
    }
    }

        BluetoothClient bluetoothClient;
        BluetoothListener bluetoothListener;
        Thread listenThread;
        bool isConnected;

 

備注:發現用兩個手機跟電腦配對成功后,兩個手機同時連上PC端軟件,一起發數據的話,PC端誰的也不接,暫時不下結論。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM