先下载InTheHand.Net.Personal.dll并在C#中引用,这个需要在网上下载
第一种、通过ObexWebRequest传输文件
先看界面
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函数,开启蓝牙监听)才可以连接。
文章来源:https://www.toymoban.com/news/detail-509458.html
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模板网!