本文實(shí)例為大家分享了C#實(shí)現(xiàn)PC藍(lán)牙通信代碼,供大家參考,具體內(nèi)容如下
添加引用InTheHand.Net.Personal.dll
首先創(chuàng)建一個(gè)藍(lán)牙類
class LanYa {public string blueName { get; set; } //l藍(lán)牙名字public BluetoothAddress blueAddress { get; set; } //藍(lán)牙的唯一標(biāo)識(shí)符public ClassOfDevice blueClassOfDevice { get; set; } //藍(lán)牙是何種類型public bool IsBlueAuth { get; set; } //指定設(shè)備通過(guò)驗(yàn)證public bool IsBlueRemembered { get; set; } //記住設(shè)備public DateTime blueLastSeen { get; set; }public DateTime blueLastUsed { get; set; }}然后就是搜索設(shè)備
List<LanYa> lanYaList = new List<LanYa>(); //搜索到的藍(lán)牙的集合BluetoothClient client = new BluetoothClient(); BluetoothRadio radio = BluetoothRadio.PrimaryRadio; //獲取藍(lán)牙適配器radio.Mode = RadioMode.Connectable; BluetoothDeviceInfo[] devices = client.DiscoverDevices();//搜索藍(lán)牙 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 });//把搜索到的藍(lán)牙添加到集合中} 藍(lán)牙的配對(duì)
BluetoothClient blueclient = new BluetoothClient();Guid mGUID1 = BluetoothService.Handsfree; //藍(lán)牙服務(wù)的uuid blueclient.Connect(s.blueAddress, mGUID) //開(kāi)始配對(duì) 藍(lán)牙4.0不需要setpin
客戶端
BluetoothClient bl = new BluetoothClient();//Guid mGUID2 = Guid.Parse("00001101-0000-1000-8000-00805F9B34FB");//藍(lán)牙串口服務(wù)的uuiidtry{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); //發(fā)送服務(wù)器端
bluetoothListener = new BluetoothListener(mGUID2);bluetoothListener.Start();//開(kāi)始監(jiān)聽(tīng)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字節(jié)}基本上就是這些吧!
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注