客户端实现蓝牙接收(C#)知识总结
客户端实现蓝牙接收(C#)知识总结
发布时间:2016-12-28 来源:查字典编辑
摘要:在实现蓝牙接收时,网上的资料很多,使用起来也很简单,但是我觉得还是有必要把这些知识总结下来。蓝牙开发需要用到一个第三方的库InTheHand...

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

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新C#教程学习
热门C#教程学习
编程开发子分类