添加引用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 }
基本上就是这些吧!
时间: 2024-10-09 06:23:10