C# 蓝牙通信
时间: 2025-05-24 11:00:01 浏览: 9
### C# 蓝牙通信 示例代码
以下是基于提供的引用内容以及专业知识整理的 C# 实现蓝牙通信的示例代码:
#### 使用 `InTheHand.Net` 库进行蓝牙设备扫描和连接
此部分展示了如何利用 `BluetoothClient` 和 `BluetoothRadio` 类来发现附近蓝牙设备并与其交互。
```csharp
using System;
using InTheHand.Net;
using InTheHand.Net.Bluetooth;
class BluetoothCommunicationExample
{
static void Main()
{
try
{
// 初始化蓝牙客户端对象
BluetoothClient client = new BluetoothClient();
// 获取本地蓝牙适配器
BluetoothRadio radio = BluetoothRadio.PrimaryRadio;
if (radio == null || !radio.IsPowered)
{
Console.WriteLine("未检测到可用的蓝牙硬件或其已关闭。");
return;
}
// 设置蓝牙模式为可连接状态
radio.Mode = RadioMode.Connectable;
// 发现附近的蓝牙设备(默认超时时间为10秒)
BluetoothDeviceInfo[] devices = client.DiscoverDevices();
// 遍历搜索到的设备列表
foreach (var device in devices)
{
Console.WriteLine($"设备名称: {device.DeviceName}, 地址: {device.DeviceAddress}");
// 假设我们需要连接名为 "MyBluetoothDevice" 的设备
if (device.DeviceName.Equals("MyBluetoothDevice"))
{
Console.WriteLine("找到了目标设备!");
// 进一步操作可以在此处扩展,例如建立流连接
Guid serviceClassUuid = BluetoothService.SerialPort; // 替换为目标服务UUID
Stream stream = client.Connect(device.DeviceAddress, serviceClassUuid);
if (stream != null)
{
Console.WriteLine("成功建立了与目标设备的连接...");
// 数据发送/接收逻辑
byte[] dataToSend = Encoding.UTF8.GetBytes("Hello from PC!");
stream.Write(dataToSend, 0, dataToSend.Length);
int bytesAvailable = stream.ReadByte();
if (bytesAvailable > 0)
{
byte[] receivedData = new byte[bytesAvailable];
stream.Read(receivedData, 0, receivedData.Length);
Console.WriteLine($"接收到的数据: {Encoding.UTF8.GetString(receivedData)}");
}
stream.Close();
}
else
{
Console.WriteLine("无法建立与目标设备的服务级连接。");
}
break;
}
}
}
catch (Exception ex)
{
Console.WriteLine($"发生错误: {ex.Message}"[^1]);
}
}
}
```
---
#### BLE 蓝牙低功耗通信示例
如果涉及的是蓝牙低功耗(BLE),则可以通过第三方库如 `Windows.Devices.Bluetooth.Advertisement` 或其他支持 BLE 的框架完成开发工作。以下是一个简单的 BLE 设备监听和写入数据的例子。
```csharp
using System;
using System.Text;
using Windows.Devices.Bluetooth.Advertisement;
class BleCommunicationExample
{
static void Main()
{
try
{
var watcher = new BluetoothLEAdvertisementWatcher();
watcher.Received += Watcher_Received;
Console.WriteLine("正在启动BLE广告监视器...");
watcher.Start();
Console.WriteLine("按 'q' 键退出程序...");
while (Console.ReadKey().KeyChar != 'q') ;
watcher.Stop();
}
catch (Exception ex)
{
Console.WriteLine($"发生错误: {ex.Message}"[^3]);
}
}
private static void Watcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
{
string deviceName = args.Advertisement.LocalName ?? "<未知>";
Console.WriteLine($"检测到BLE设备: 名称={deviceName}, RSSI={args.RawSignalStrengthInDBm} dBm");
// 如果需要进一步处理特定设备,则可以根据条件筛选
if (!string.IsNullOrEmpty(args.Advertisement.ServiceUuids))
{
foreach (var uuid in args.Advertisement.ServiceUuids)
{
Console.WriteLine($"服务 UUID: {uuid}");
}
}
// 可选:向该设备写入数据
// 注意此处需额外实现 GATT 特征值访问功能
}
}
```
---
#### 关键点说明
- **库依赖**:对于经典蓝牙通信,推荐使用 `InTheHand.Net.Sockets` NuGet 包;而对于 BLE 开发,在 UWP 平台下建议采用 Microsoft 提供的 API。
- **权限配置**:确保应用程序具有必要的权限声明(如位置、蓝牙等)。这通常需要修改项目的清单文件或在运行时请求授权[^4]。
- **异常捕获**:由于蓝牙环境复杂多变,务必加入全面的异常处理机制以提升稳定性。
---
阅读全文
相关推荐

















