程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> PC上面的藍牙的通信(C#),

PC上面的藍牙的通信(C#),

編輯:C#入門知識

PC上面的藍牙的通信(C#),


添加引用InTheHand.Net.Personal.dll

首先創建一個藍牙類

1 class LanYa {
2 public string blueName { get; set; }                                   //l藍牙名字
3 public BluetoothAddress blueAddress { get; set; }               //藍牙的唯一標識符
4 public ClassOfDevice blueClassOfDevice { get; set; }            //藍牙是何種類型
5 public bool IsBlueAuth { get; set; }                                    //指定設備通過驗證
6 public bool IsBlueRemembered { get; set; }                        //記住設備
7 public DateTime blueLastSeen { get; set; }
8 public DateTime blueLastUsed { get; set; }
9 }

 

然後就是搜索設備

1 List<LanYa> lanYaList = new List<LanYa>();                //搜索到的藍牙的集合
2 BluetoothClient client = new BluetoothClient();            
3 BluetoothRadio radio = BluetoothRadio.PrimaryRadio;  //獲取藍牙適配器
4 radio.Mode = RadioMode.Connectable;                        
5 BluetoothDeviceInfo[] devices = client.DiscoverDevices();//搜索藍牙  10秒鐘
6 foreach (var item in devices) {
7 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 });//把搜索到的藍牙添加到集合中
8 }

 

藍牙的配對

1 BluetoothClient blueclient = new BluetoothClient();
2 Guid mGUID1 = BluetoothService.Handsfree;       //藍牙服務的uuid
3 
4  blueclient.Connect(s.blueAddress, mGUID)      //開始配對  藍牙4.0不需要setpin

 

客戶端

 1 BluetoothClient bl = new BluetoothClient();//
 2 Guid mGUID2 = Guid.Parse("00001101-0000-1000-8000-00805F9B34FB");//藍牙串口服務的uuiid
 3 
 4 try
 5 {
 6 bl.Connect(s.blue_address, mGUID);
 7 //"連接成功";
 8 }
 9 catch(Exception x)
10 {
11 //異常
12 }
13 
14 var v = bl.GetStream();
15 byte[] sendData = Encoding.Default.GetBytes(“人生苦短,我用python”);
16 v.Write(sendData, 0, sendData.Length);              //發送

 

 

服務器端

 1 bluetoothListener = new BluetoothListener(mGUID2);
 2 bluetoothListener.Start();//開始監聽
 3 
 4 bl = bluetoothListener.AcceptBluetoothClient();//接收
 5 
 6 
 7 while (true)
 8 {
 9 byte[] buffer = new byte[100];
10 Stream peerStream = bl.GetStream();
11 
12 peerStream.Read(buffer, 0, buffer.Length);
13 
14 string data= Encoding.UTF8.GetString(buffer).ToString().Replace("\0", "");//去掉後面的\0字節
15 }

 

基本上就是這些吧!

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved