The client realizes bluetooth receiving of C knowledge summary

  • 2020-05-09 19:06:13
  • OfStack

When realizing bluetooth reception, there are a lot of information on the Internet and it is easy to use, but I think it is necessary to summarize the knowledge. Bluetooth development needs to use a third party library InTheHand.Net.Personal.dll, among which the two key classes are BluetoothClient and BluetoothListener. First, open a sub-thread to continuously receive data.
 
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; 

Note: it is found that after successfully pairing the two phones with the computer, the two phones are connected to the PC software at the same time. If the data is sent from the first one, no one will be connected to the PC terminal, so no conclusion can be reached for the time being.

Related articles: