欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PC蓝牙通信C#代码实现

程序员文章站 2022-04-15 09:33:37
本文实例为大家分享了c#实现pc蓝牙通信代码,供大家参考,具体内容如下 添加引用inthehand.net.personal.dll 首先创建一个蓝牙类 cl...

本文实例为大家分享了c#实现pc蓝牙通信代码,供大家参考,具体内容如下

添加引用inthehand.net.personal.dll

首先创建一个蓝牙类

class lanya {
public string bluename { get; set; }                  //l蓝牙名字
public bluetoothaddress blueaddress { get; set; }        //蓝牙的唯一标识符
public classofdevice blueclassofdevice { get; set; }      //蓝牙是何种类型
public bool isblueauth { get; set; }                  //指定设备通过验证
public bool isblueremembered { get; set; }            //记住设备
public datetime bluelastseen { get; set; }
public datetime bluelastused { get; set; }
}
 

然后就是搜索设备

list<lanya> lanyalist = new list<lanya>();        //搜索到的蓝牙的集合
bluetoothclient client = new bluetoothclient();      
bluetoothradio radio = bluetoothradio.primaryradio; //获取蓝牙适配器
radio.mode = radiomode.connectable;            
bluetoothdeviceinfo[] devices = client.discoverdevices();//搜索蓝牙 10秒钟
foreach (var item in devices) {
lanyalist.add(new lanya { bluename = item.devicename, blueaddress = item.deviceaddress, blueclassofdevice = item.classofdevice, isblueauth = item.authenticated, isblueremembered = item.remembered, bluelastseen = item.lastseen, bluelastused = item.lastused });//把搜索到的蓝牙添加到集合中
}
 

蓝牙的配对

bluetoothclient blueclient = new bluetoothclient();
guid mguid1 = bluetoothservice.handsfree;    //蓝牙服务的uuid
 
blueclient.connect(s.blueaddress, mguid)   //开始配对 蓝牙4.0不需要setpin
 

客户端

bluetoothclient bl = new bluetoothclient();//
guid mguid2 = guid.parse("00001101-0000-1000-8000-00805f9b34fb");//蓝牙串口服务的uuiid

try
{
bl.connect(s.blue_address, mguid);
//"连接成功";
}
catch(exception x)
{
//异常
}

var v = bl.getstream();
byte[] senddata = encoding.default.getbytes(“人生苦短,我用python”);
v.write(senddata, 0, senddata.length);       //发送

服务器端

bluetoothlistener = new bluetoothlistener(mguid2);
bluetoothlistener.start();//开始监听

bl = bluetoothlistener.acceptbluetoothclient();//接收


while (true)
{
byte[] buffer = new byte[100];
stream peerstream = bl.getstream();

peerstream.read(buffer, 0, buffer.length);

string data= encoding.utf8.getstring(buffer).tostring().replace("\0", "");//去掉后面的\0字节
}

基本上就是这些吧!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。