PC藍牙通訊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字節
}

基本上就是這些吧!
相關文章
相關標籤/搜索