在实现蓝牙接收时,网上的资料很多,使用起来也很简单,但是我觉得还是有必要把这些知识总结下来。蓝牙开发需要用到一个第三方的库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端谁的也不接,暂时不下结论。