C#蓝牙连接及传输数据的三种方式(蓝牙传输文件、二进制数据)

这篇具有很好参考价值的文章主要介绍了C#蓝牙连接及传输数据的三种方式(蓝牙传输文件、二进制数据)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

      先下载InTheHand.Net.Personal.dll并在C#中引用,这个需要在网上下载

第一种、通过ObexWebRequest传输文件

     先看界面

C#蓝牙连接及传输数据的三种方式(蓝牙传输文件、二进制数据)

 

using InTheHand.Net;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Sockets;
using InTheHand.Windows.Forms;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Frmbtooth : Form
    {

        BluetoothRadio radio = null;//蓝牙适配器  
        string sendFileName = null;//发送文件名  
        BluetoothAddress sendAddress = null;//发送目的地址  
        ObexListener listener = null;//监听器  
        string recDir = null;//接受文件存放目录  
        Thread listenThread, sendThread;//发送/接收线程
        BluetoothClient Blueclient;
        bool isbluelisten = false;
        public Frmbtooth()
        {
            InitializeComponent();
            radio = BluetoothRadio.PrimaryRadio;//获取当前PC的蓝牙适配器  
            CheckForIllegalCrossThreadCalls = false;//不检查跨线程调用  
            if (radio == null)//检查该电脑蓝牙是否可用  
            {
                MessageBox.Show("这个电脑蓝牙不可用!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                Blueclient = new BluetoothClient();
            }
            recDir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            textBox1.Text = recDir;
        }
        Dictionary<string, BluetoothAddress> deviceAddresses = new Dictionary<string, BluetoothAddress>();
        OpenFileDialog dialog = new OpenFileDialog();
        private void button2_Click(object sender, EventArgs e)
        {
            
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                sendFileName = dialog.FileName;//设置文件名  
                labelPath.Text = Path.GetFileName(sendFileName);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SelectBluetoothDeviceDialog dialog = new SelectBluetoothDeviceDialog();
            dialog.ShowRemembered = true;//显示已经记住的蓝牙设备  
            dialog.ShowAuthenticated = true;//显示认证过的蓝牙设备  
            dialog.ShowUnknown = true;//显示位置蓝牙设备  
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                sendAddress = dialog.SelectedDevice.DeviceAddress;//获取选择的远程蓝牙地址  
                labelAddress.Text = "地址:" + sendAddress.ToString() + " 设备名:" + dialog.SelectedDevice.DeviceName;
            }
        }
        private void sendFile()//发送文件方法  
        {
            ObexWebRequest request = new ObexWebRequest(sendAddress, Path.GetFileName(sendFileName));//创建网络请求  
            WebResponse response = null;
            try
            {
                buttonSend.Enabled = false;
                request.ReadFile(sendFileName);//发送文件  
                labelInfo.Text = "开始发送!";
                response = request.GetResponse();//获取回应  
                labelInfo.Text = "发送完成!";
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("发送失败!"+ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                labelInfo.Text = "发送失败!";
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    buttonSend.Enabled = true;
                }
            }
        }

        SerialPort BluetoothConnection = new SerialPort();
        int length = 20;
        string BlueToothReceivedData = "";
        

        private void button3_Click_1(object sender, EventArgs e)
        {
            sendThread = new Thread(sendFile);//开启发送文件线程  
            sendThread.Start();
        }

        private void buttonListen_Click(object sender, EventArgs e)
        {
            if (listener == null || !listener.IsListening)
            {
                radio.Mode = RadioMode.Discoverable;//设置本地蓝牙可被检测  
                listener = new ObexListener(ObexTransport.Bluetooth);//创建监听  
                listener.Start();
                if (listener.IsListening)
                {
                    buttonListen.Text = "停止";
                    labelRecInfo.Text = "开始监听";
                    listenThread = new Thread(receiveFile);//开启监听线程  
                    listenThread.Start();
                }
            }
            else
            {
                listener.Stop();
                buttonListen.Text = "监听";
                labelRecInfo.Text = "停止监听";
            }
        }

        private void buttonselectRecDir_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择蓝牙接收文件的存放路径";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                recDir = dialog.SelectedPath;
                labelRecDir.Text = recDir;
            }
        }

        private void Frmbtooth_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (sendThread != null)
            {
                sendThread.Abort();
            }
            if (listenThread != null)
            {
                listenThread.Abort();
            }
            if (listener != null && listener.IsListening)
            {
                listener.Stop();
            }
        }
       
        private void receiveFile()//收文件方法  
        {
            ObexListenerContext context = null;
            ObexListenerRequest request = null;
            while (listener.IsListening)
            {
                context = listener.GetContext();//获取监听上下文  
                if (context == null)
                {
                    break;
                }
                request = context.Request;//获取请求  
                string uriString = Uri.UnescapeDataString(request.RawUrl);//将uri转换成字符串  
                string recFileName = recDir + uriString;
                request.WriteFile(recFileName);//接收文件  
                
                labelRecInfo.Text = "收到文件" + uriString.TrimStart(new char[] { '/' });
            }
        }

    }
}

         这种方式优点是稳定性较强,基本无错误,就是偶尔需要提前蓝牙配对。

第二种、通过BluetoothClient传输二进制数据

using InTheHand.Net;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Sockets;
using InTheHand.Windows.Forms;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Frmbtooth : Form
    {

        BluetoothRadio radio = null;//蓝牙适配器  
        string sendFileName = null;//发送文件名  
        BluetoothAddress sendAddress = null;//发送目的地址  
        ObexListener listener = null;//监听器  
        string recDir = null;//接受文件存放目录  
        Thread listenThread, sendThread;//发送/接收线程
        BluetoothClient Blueclient;
        bool isbluelisten = false;
        public Frmbtooth()
        {
            InitializeComponent();
            radio = BluetoothRadio.PrimaryRadio;//获取当前PC的蓝牙适配器  
            CheckForIllegalCrossThreadCalls = false;//不检查跨线程调用  
            if (radio == null)//检查该电脑蓝牙是否可用  
            {
                MessageBox.Show("这个电脑蓝牙不可用!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                Blueclient = new BluetoothClient();
            }
            recDir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            textBox1.Text = recDir;
        }

      
        Dictionary<string, BluetoothAddress> deviceAddresses = new Dictionary<string, BluetoothAddress>();
        OpenFileDialog dialog = new OpenFileDialog();
        private void button2_Click(object sender, EventArgs e)
        {
            
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                sendFileName = dialog.FileName;//设置文件名  
                labelPath.Text = Path.GetFileName(sendFileName);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SelectBluetoothDeviceDialog dialog = new SelectBluetoothDeviceDialog();
            dialog.ShowRemembered = true;//显示已经记住的蓝牙设备  
            dialog.ShowAuthenticated = true;//显示认证过的蓝牙设备  
            dialog.ShowUnknown = true;//显示位置蓝牙设备  
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                sendAddress = dialog.SelectedDevice.DeviceAddress;//获取选择的远程蓝牙地址  
                labelAddress.Text = "地址:" + sendAddress.ToString() + " 设备名:" + dialog.SelectedDevice.DeviceName;
            }
        }
       
        SerialPort BluetoothConnection = new SerialPort();
        int length = 20;
        string BlueToothReceivedData = "";
        private void button3_Click(object sender, EventArgs e)
        {
            BluetoothClient cli = new BluetoothClient();
            string strimg = dialog.FileName.ToString();  //记录图片的所在路径
            FileStream fs = new FileStream(strimg.Replace(".jpg", ".dat"), FileMode.Open, FileAccess.Read); //将图片以文件流的形式进行保存
            BinaryReader br = new BinaryReader(fs);
            byte[] imgBytesIn = br.ReadBytes((int)fs.Length);//将流读入到字节数组中
            fs.Close();
            br.Close();
            BluetoothEndPoint ep = null;
            try
            {
                // [注意2]:要注意MAC地址中字节的对应关系,直接来看顺序是相反的,例如
                // 如下对应的MAC地址为——12:34:56:78:9a:bc
                ep = new BluetoothEndPoint(sendAddress, BluetoothService.SerialPort);
                //ep = new BluetoothEndPoint(sendAddress, Guid.Parse("e0cbf06c-cd8b-4647-bb8a-263b43f0f974"));
                //ep = new BluetoothEndPoint(sendAddress, BluetoothService.Handsfree);
                Console.WriteLine("正在连接!");
               // cli.SetPin("0000");
                cli.Connect(ep); // 连接蓝牙
               
                if (cli.Connected)
                {
                    
                    Stream peerStream = cli.GetStream();
                    byte[] sendData = Encoding.Default.GetBytes("人生苦短,我用python");
                    //peerStream.Write(imgBytesIn, 0, imgBytesIn.Length);
                    peerStream.Write(sendData, 0, sendData.Length);
                    // peerStream.WriteByte(0xBB); // 发送开门指令
                }
                else
                {
                    MessageBox.Show("端口1没打开");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (cli != null)
                {
                    // [注意3]:要延迟一定时间(例如1000毫秒)
                    //避免因连接后又迅速断开而导致蓝牙进入异常(傻逼)状态
                    Thread.Sleep(1000);
                    cli.Close();
                }
            }
           
        }
        private void Frmbtooth_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (sendThread != null)
            {
                sendThread.Abort();
            }
            if (listenThread != null)
            {
                listenThread.Abort();
            }
            if (listener != null && listener.IsListening)
            {
                listener.Stop();
            }
        }

      
       
        public void bluelisten()
        {
            BluetoothListener bluetoothListener = null;
            Guid mGUID2 = Guid.Parse("00001101-0000-1000-8000-00805F9B34FB");//蓝牙串口服务的uuiid
            bluetoothListener = new BluetoothListener(mGUID2);
            bluetoothListener.Start();//开始监听
            Console.WriteLine("开始监听");
            while (isbluelisten)
            {
                var bl = bluetoothListener.AcceptBluetoothClient();//接收
                byte[] buffer = new byte[100];
                Stream peerStream = bl.GetStream();
                peerStream.Read(buffer, 0, buffer.Length);
                //string data = Encoding.UTF8.GetString(buffer).ToString()
                        ;//去掉后面的字节
                Console.WriteLine(buffer);
                
            }
            bluetoothListener.Stop();
        }
        private void button6_Click(object sender, EventArgs e)
        {
            if (!isbluelisten)
            {
                isbluelisten = true;
                radio.Mode = RadioMode.Discoverable;//设置本地蓝牙可被检测  
                button6.Text = "停止";
                labelRecInfo.Text = "开始监听";
                listenThread = new Thread(bluelisten);//开启监听线程  
                listenThread.Start();
                
            }
            else
            {
                button6.Text = "配对监听";
                labelRecInfo.Text = "停止监听";
                isbluelisten = false;
            }
        }
    }
}

       这种方式直接与蓝牙设备进行配对的时候会报错,请求的地址无效,这时候需要在被检测的蓝牙设备开启BluetoothListener 默认UUID是"00001101-0000-1000-8000-00805F9B34FB"即蓝牙串口服务的UUID。

        手机设备开启蓝牙服务可以下载“蓝牙串口”应用,打开蓝牙服务串口。

第三种、通过蓝牙串口方式传输二进制数据 

需要在电脑蓝牙设置中添加蓝牙串口,传入传出两个方向的蓝牙串口都需要有,传出串口配置的时候需要让被测蓝牙设备打开蓝牙服务串口(也就是上一种方法中的bluelisten函数,开启蓝牙监听)才可以连接。

C#蓝牙连接及传输数据的三种方式(蓝牙传输文件、二进制数据)

SerialPort BluetoothConnection = new SerialPort();
        int length = 20;
        string BlueToothReceivedData = "";
        private void button4_Click(object sender, EventArgs e)
        {
            string[] Ports = SerialPort.GetPortNames();
            for (int i = 0; i < Ports.Length; i++)
            {
                string name = Ports[i];
                comboBox.Items.Add(name);//显示在消息框里面
            }
        }
        private void button5_Click(object sender, EventArgs e)
        {
            byte[] head = new byte[8] { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 };//随便写的一组数据,里面的数据无意

            try
            {
                BluetoothConnection.PortName = comboBox.Text;
                BluetoothConnection.BaudRate = 9600;
                BluetoothConnection.Open();//打开蓝牙串口
                BluetoothConnection.WriteTimeout = 10000;
                if (BluetoothConnection.IsOpen)
                {
                    BlueToothReceivedData = " d1_on";
                    MessageBox.Show("端口已打开");
                    BlueToothReceivedData = " d1_on";
                    //BluetoothConnection.Write(head, 0, head.Length);
                    BluetoothConnection.Write("12323");
                    BluetoothConnection.Read(head, 0, head.Length);
                    //  BluetoothConnection.DataReceived += SerialPort_DataReceived;
                    Console.WriteLine(BluetoothConnection.BytesToWrite.ToString());
                    // Thread.Sleep(1000);
                    MessageBox.Show("完成");
                }
                //BluetoothConnection.WriteLine(BlueToothReceivedData);
                //byte[] head = new byte[8] { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 };//随便写的一组数据,里面的数据无意义

            }
            catch (Exception ex)
            {
                label1.Text = "发送失败" + ex.Message;
            }
        }
        private void get_Click(object sender, EventArgs e)
        {
            byte[] data = new byte[length];
            try
            {
                BluetoothConnection.Read(data, 0, length);
            }
            catch
            {
                label1.Text = " 接受失败";
            }
            for (int i = 0; i < length; i++)
            {
                BlueToothReceivedData += string.Format("data[{0}] = {1}\r\n", i, data[i]);//"+="表示接收数据事件发生时,触发"+="后面的语句
            }
        }

​​​​​​​​​​​​​​就这样,有问题评论区留言。 文章来源地址https://www.toymoban.com/news/detail-509458.html

到了这里,关于C#蓝牙连接及传输数据的三种方式(蓝牙传输文件、二进制数据)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【Qt】信号槽的三种连接方式

    实现观察者模式,可以使用函数回调,但注册回调函数有一定局限,安全性也没有保证。所以一定程度上可以说 Qt 信号槽是对回调机制进行了封装。 Qt 的信号槽能够连接(connect) 和编译通过,需要满足两个条件 信号的参数个数大于等于槽函数 信号槽的参数个数相同的部分,

    2024年02月13日
    浏览(32)
  • 路由器连接电脑的三种方式和设置介绍

    路由器怎么连接电脑进行设置呢?目前随着电脑、智能手机、平板电脑等网络设备的普及,人们对网络的需求日益增加,因此推动了路由器的广泛使用。不过很多大多数用户不知道怎样把路由器和电脑连接起来,然后进行后续的配置。 路由器与电脑之间的连接方式有两种,一

    2024年02月08日
    浏览(34)
  • ADB连接手机的三种方式USB、WLAN、WIFI

    这三种方式都需要将手机的开发者模式打开,否者无法连接手机。在“设置-我的设备-全部参数”找到手机版本,连续点击7次会进入开发者模式。 进入开发者选项页面,把USB调试、USB安装都打开,然后才能正常的进行连接。    1、第一种连接方式:USB连接         需要用可

    2024年02月05日
    浏览(46)
  • Java创建文件的三种方式

    内容来自于韩顺平学Java 在学习其视频下跟着编写 文件创建成功

    2024年04月11日
    浏览(51)
  • python生成excel文件的三种方式

    在我们做平常工作中都会遇到操作excel,那么今天写一篇,如何通过python操作excel。当然python操作excel的库有很多,比如pandas,xlwt/xlrd,openpyxl等,每个库都有不同的区别,具体的区别,大家一起来看看吧~ xlrd是对于Excel进行读取,xlrd 操作的是xls/xlxs格式的excel xlwt是对于Excel进

    2024年02月15日
    浏览(29)
  • Windows下生成dump文件的三种方式

    提示:本文为描述windows平台下的dump文件生成: windows程序当遇到异常,没有try-catch或者try-catch也无法捕获到的异常时,程序就会自动退出。 windows系统默认是不产生程序dmp文件的。dump文件是C++程序发生异常时,保存当时程序运行状态的文件。 是调试异常程序重要的方法。 简

    2023年04月08日
    浏览(64)
  • windows和虚拟机互传文件的三种方式

    大家好,在平时学习工作的时候可能有这样的需求:要将windows中的文件传到虚拟机中或者将虚拟机的文件传到windows,大家都是怎么实现的呢? 今天给大家介绍下windows和虚拟机互传文件的三种方式,希望能对大家有所帮助。 方法一:使用U盘进行传输 大家都是聪明人,这个方

    2023年04月16日
    浏览(27)
  • linux:文件替换的三种方式sed、awk、perl

    linux 文件内容替换,网上看了下大致就这三种 sed、awk、perl,今天挨个使用一下看看怎么样 语法 Linux sed 命令是利用脚本来处理文本文件。详细文档 搭配 find 可以对文件夹进行查找替换: find ./ -name \\\"*.js\\\" | xargs sed -i \\\'\\\' \\\'s/aaa/hhh/g\\\' 问题 一般在 linux 上该命令就可以生效。 但是我

    2024年02月03日
    浏览(39)
  • docker 数据挂载的三种方式

    目录 前言 更详细的Diff 适合Volumes的场景 适合bind mounts的场景 适合tmpfs mounts的场景 使用 前言 回到目录 我们可以将数据写到容器的可写入层,但是这种写入是有缺点的: 当容器停止运行时,写入的数据会丢失。你也很难将这些数据从容器中取出来给另外的应用程序使用。 容

    2024年02月06日
    浏览(46)
  • Hive:元数据的三种部署方式

    1.内嵌模式示意图: 2.Derby数据库: Derby数据库是Java编写的内存数据库,在内嵌模式中与应用程序共享一个JVM,应用程序负责启动和停止。 初始化Derby数据库 1)在hive根目录下,使用/bin目录中的schematool命令初始化hive自带的Derby元数据库 [atguigu@hadoop102 hive]$ bin/schematool -dbType

    2024年01月17日
    浏览(34)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包