客户端实现蓝牙接收(C#)知识总结
时间:2020-11-08 12:08:03|栏目:.NET代码|点击: 次
在实现蓝牙接收时,网上的资料很多,使用起来也很简单,但是我觉得还是有必要把这些知识总结下来。蓝牙开发需要用到一个第三方的库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端谁的也不接,暂时不下结论。
复制代码 代码如下:
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端谁的也不接,暂时不下结论。
上一篇:AspNetPager分页控件定义及应用样式示例介绍
栏 目:.NET代码
下一篇:Asp.net实现无刷新调用后台实体类数据并以Json格式返回
本文标题:客户端实现蓝牙接收(C#)知识总结
本文地址:http://www.codeinn.net/misctech/20245.html