在實現藍牙接收時,網上的資料很多,使用起來也很簡單,但是我覺得還是有必要把這些知識總結下來。藍牙開發需要用到一個第三方的庫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端誰的也不接,暫時不下結論。