Windows下使用C#和32feet.NET开发蓝牙传输功能的记录
引用的第三方Nuget库
- 32feet.NET 3.5.0
- MaterialDesignColors
- MaterialDesignThemes
- Newtonsoft.Json
使用到的技术:
XAML C#
本实例中使用的蓝牙是作为服务器端等待连接.
主要流程如下:
第1步
初始化相关内容:
public static void InitSDK()
{
Guid mGUID = Guid.Parse("00001101-0000-1000-8000-00805F9B34FB");
bluetoothListener = new BluetoothListener(mGUID);
}
其中00001101-0000-1000-8000-00805F9B34FB是蓝牙串口服务的uuid,其他类型的服务uuid各有不同,可以查阅相关资料
第2步
声明蓝牙监听对象:
BluetoothListener bluetoothListener;
第3步
等待蓝夜客户端进行连接:
client = bluetoothListener.AcceptBluetoothClient();
获取客户端连接对象的信息(类似于TCP连接):
bluetoothModel.blueAddress = client.RemoteEndPoint.Address;
bluetoothModel.blueName = client.RemoteMachineName;
通知调用,通知注册的事件已经有蓝牙连接成功:
public static void Notify(object message)
{
NotifyMessage?.Invoke(message);
}
Notify(bluetoothModel);
接收数据并解析:
while (true)
{
try
{
if (peerStream.DataAvailable)
{
peerStream.ReadAsync(buffer, 0, 1024);
//peerStream.Read(buffer, 0, 200);
string data = Encoding.UTF8.GetString(buffer).ToString().Replace("\0", "");//去掉后面的\0字节
Console.WriteLine("Receiving data: " + data);
//if (peerStream.Length > 0)
//{
//}
}
}
catch (Exception ex)
{
client.Close();
Notify("链接关闭");
MessageBox.Show(ex.Message);
return;
}
}
作为服务器要一直监听客户端发送的消息,所以进行死循环接收(这种方案比较简单,可以使用异步委托重复调用进行优化)
缓冲区大小设置为1024的长度,没有做按照标准进行处理,此项目中不接受数据,所以没有展开写.
发送
发送数据
public static void Send(string str)
{
if (peerStream != null)
{
if (peerStream.CanWrite)
{
List<byte> list = new List<byte>();
byte header = 0x01;
list.Add(header);
byte[] dataBuffer = Encoding.UTF8.GetBytes(str);
foreach (var item in dataBuffer)
{
list.Add(item);
}
try
{
// Output data to stream
peerStream.Write(list.ToArray(), 0, list.Count);
peerStream.Flush();
}
catch (Exception ex)
{
client.Close();
Notify("链接关闭");
MessageBox.Show(ex.Message);
}
}
else
{
client.Close();
Notify("链接关闭");
MessageBox.Show("配对失败内侧");
}
}
else
{
MessageBox.Show("配对失败外侧");
}
}
发送数据遵从一定的协议,超过1024即1K字节长度则分包发送
其中0x01代表发送字符串,0x02代表发送文件
发送文件:
//1 文件类型
//1 文件子类型
//4 文件大小
//4 总包数
//4 第几包
//4 本包大小
public static void SendFile(int type, string filePath)
{
if (peerStream != null)
{
int packCount = 512 - 17;
byte btype = (byte)type;
byte[] img = File.ReadAllBytes(filePath);
int imgLength = img.Length;
Console.WriteLine("图像长度:" + imgLength);
byte[] blen = intToBytes(imgLength);
List<byte> original = new List<byte>(img.ToArray());
List<List<byte>> targetList = new List<List<byte>>();
int totalCount = img.Length / packCount + 1;
byte[] btotalCount = intToBytes(totalCount);
for (int i = 0; i < totalCount - 1; i++)
{
List<byte> curList = new List<byte>();
curList.Add(0x02);
curList.Add(btype);
//总文件长度
curList.AddRange(blen);
//总包数
curList.AddRange(btotalCount);
byte[] bForNoCount = intToBytes(i);
//第几包
curList.AddRange(bForNoCount);
//本包大小
byte[] curCount = intToBytes(packCount);
curList.AddRange(curCount);
//包内容
curList.AddRange(original.GetRange(i * packCount, packCount));
targetList.Add(curList);
}
List<byte> lastList = new List<byte>();
lastList.Add(0x02);
lastList.Add(btype);
lastList.AddRange(blen);
//总包数
lastList.AddRange(btotalCount);
byte[] bNoCount = intToBytes(totalCount - 1);
//第几包
lastList.AddRange(bNoCount);
//包大小
byte[] lastCount = intToBytes(imgLength - (totalCount - 1) * packCount);
lastList.AddRange(lastCount);
lastList.AddRange(original.GetRange((totalCount - 1) * packCount, imgLength - (totalCount - 1) * packCount));
//lastList.Add((Byte)('\n'));
targetList.Add(lastList);
if (peerStream.CanWrite)
{
foreach (var item in targetList)
{
try
{
Console.WriteLine("包长:" + item.Count);
peerStream.Write(item.ToArray(), 0, item.Count);
peerStream.Flush();
}
catch (Exception ex)
{
//Console.WriteLine(ex);
MessageBox.Show(ex.Message);
return;
}
}
}
}
}
文件一般大于1K,所以分包发送.基本协议见方法注释.
代码比较粗糙,毕竟只是一次性项目,没有花很多信息分层,优化,写注释等,看客们请谅解,学习到精髓就可以了
详细代码见github链接
[链接](https://github.com/KleinPan/WpfAppBluetooth)
Windows下使用C#和32feet.NET开发蓝牙传输功能的记录的更多相关文章
- windows下使用vs进行Proctocol Buffer开发(C++篇)
因工作原因接触Proctocol Buffer(protobuf),至于什么是protobuf,为何使用protobuf,我就不赘述了,百度下都是答案. 今天我介绍的是在windows下使用vs进行p ...
- Windows下visual studio code搭建golang开发环境
Windows下visual studio code搭建golang开发环境 序幕 其实环境搭建没什么难的,但是遇到一些问题,主要是有些网站资源访问不了(如:golang.org),导致一些包无法安装 ...
- 在 Windows 下用 TDM-GCC(MinGW)开发 DLL 涉及到数据同步锁及 DLL 初始化终止化函数的问题
在 Windows 下用 TDM-GCC(MinGW)开发 DLL 如果要用到数据同步锁,理论上可以采用 Windows API 提供的临界区实现(需要用到的函数有 InitializeCritica ...
- Windows下nginx的启动,重启,关闭功能
@echo off rem 提供Windows下nginx的启动,重启,关闭功能 echo ==================begin======================== cls :: ...
- Windows下用Eclipse搭建C/C++开发环境
本文假定你已经熟悉Java,Eclipse的安装,并能顺利启动和运行Eclipse.此外因为各软件版本在不断更新,有些地方可能不准确,以最新的.原文资料为准. 距上一次写和调C++程序,已经5.6年了 ...
- Windows 下使用 MinGW 和 CMake 进行开发
CMake 是个非常棒的项目管理工具,这已经是毋庸置疑的. 一些小工具需要在 win 下开发,所以今天探索使用 MinGW 和 CMake 在 win 下的搭配使用.简单做记录. MinGW 使用 Q ...
- windows下sublime text的node.js开发环境搭建
首先安装sublime text3,百度一堆,自己找吧.理论上sublime text2应该也可以.我只能说一句:这个软件实在是太强悍了. 跨平台,丰富的插件体系,加上插件基本上就是一个强悍的ide了 ...
- windows下用ADT进行android NDK开发的具体教程(从环境搭建、配置到编译全过程)
郑重申明:如需转载本博客,请注明出处,谢谢! 这几天在学习android NDK的开发.那么首先让我们来看看android NDK开发的本质是什么. NDK(Native Development Ki ...
- 不用rustup,Windows下gnu版Rust安装与开发环境配置
写在前面 本文介绍了在不使用rustup的情况下,在Windows上安装gnu版的Rust,并配置开发环境(VSCode + rust-analyzer,CLion + IntelliJ Rust)的 ...
- Windows下几款免费C/C++开发工具简介
我相信作为编程初学者,我们都希望有好用的编程软件.这里"好用"应该至少要满足两点:1.安装简单,2.使用方便.大神移驾,对工具有特殊偏好跳过,从来不用Windows的止步.本文不做 ...
随机推荐
- Stream流的应用
Stream流的应用 Collectors.groupingBy(ShopCartItemDto::getShopId) stream()方法将该列表转化为一个流,可以对其中的元素进行操作. coll ...
- HTML一键打包APK工具1.9.5更新,新增一机一码功能
HMTL网址打包APK,可以把本地HTML项目, Egret游戏,网页游戏,或者网站打包为一个安卓应用APK文件,无需编写任何代码,也无需配置安卓开发环境,支持在最新的安卓设备上安装运行. 打包软件会 ...
- 聊聊基于Alink库的主成分分析(PCA)
概述 主成分分析(Principal Component Analysis,PCA)是一种常用的数据降维和特征提取技术,用于将高维数据转换为低维的特征空间.其目标是通过线性变换将原始特征转化为一组新的 ...
- 拟合优度R2较低怎么办
拟合优度R2较低怎么办 (1)回归分为解释型回归和预测型回归. 预测型回归一般才会更看重2. 解释型回归更多的关注模型整体显著性以及自变量的统计显著性和经济意义显著 性即可. (2)可以对模型进行调整 ...
- c语言代码练习10
//判断输入的数字是否为素数#define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> int main() { int n = 0; int ...
- Jellyfin Documentation
Skip to main content Introduction On this page Welcome to the Jellyfin Documentation Jellyfin is ...
- Appendix D. Gradle Command Line
http://www.gradle.org/docs/current/userguide/gradle_command_line.html Appendix D. Gradle Command Lin ...
- 教育法学第七章单元测试MOOC
第七章单元测试 返回 本次得分为:100.00/100.00, 本次测试的提交时间为:2020-09-06, 如果你认为本次测试成绩不理想,你可以选择 再做一次 . 1 单选(5分) 父母对未成年子女 ...
- 安装 Android x86 并开启 arm 兼容
安装 Android x86 并开启 arm 兼容 Win 11 下开启了 Hyper-v,尝试了各种安卓模拟器,要么不能设置代理(BlueStacks),要么/system目录没办法设置. 获取 A ...
- mybatis 操作 mysql 动态创建数据表
Map 数据一般是根据需求生成的,例如 map.put("ticketId",176),map.put("ticketName","测试工单" ...