PC藍牙通信C#代碼實現(xiàn)
更新時間:2016年09月28日 15:16:04 作者:名字好難
這篇文章主要為大家詳細介紹了PC藍牙通信C#代碼實現(xiàn),具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了C#實現(xiàn)PC藍牙通信代碼,供大家參考,具體內容如下
添加引用InTheHand.Net.Personal.dll
首先創(chuàng)建一個藍牙類
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); //發(fā)送
服務器端
bluetoothListener = new BluetoothListener(mGUID2); bluetoothListener.Start();//開始監(jiān)聽 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é) }
基本上就是這些吧!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
C#基礎知識系列八const和readonly關鍵字詳細介紹
這篇文章主要介紹了C#中的const和readonly關鍵字,有需要的朋友可以參考一下2014-01-01