1. 程式人生 > >c# 藍芽 自己借鑑

c# 藍芽 自己借鑑

PC藍芽通訊C#程式碼實現

這篇文章主要為大家詳細介紹了PC藍芽通訊C#程式碼實現,具有一定的參考價值,感興趣的小夥伴們可以參考一下
本文例項為大家分享了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位元組
}