客户端实现蓝牙接收(C#)知识总结
程序员文章站
2023-12-11 23:41:28
在实现蓝牙接收时,网上的资料很多,使用起来也很简单,但是我觉得还是有必要把这些知识总结下来。蓝牙开发需要用到一个第三方的库inthehand.net.personal.dl...
在实现蓝牙接收时,网上的资料很多,使用起来也很简单,但是我觉得还是有必要把这些知识总结下来。蓝牙开发需要用到一个第三方的库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端谁的也不接,暂时不下结论。