C#蓝牙链接+传输文件

 先下载InTheHand.Net.Personal.dll并在C中引用

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Forms;
using InTheHand.Net;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Sockets;
using InTheHand.Windows.Forms;
using System.Net;
using System.IO;
using System.IO.Ports;

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

        BluetoothClient Blueclient = new BluetoothClient();
        Dictionary<string, BluetoothAddress> deviceAddresses = new Dictionary<string, BluetoothAddress>();

        private void Form1_Load(object sender, EventArgs e)
        {
            
        }



        private void buttonSelectBluetooth_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 buttonSelectFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                sendFileName = dialog.FileName;//设置文件名  
                labelPath.Text = Path.GetFileName(sendFileName);
            }
        }

        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 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 buttonSend_Click(object sender, EventArgs e)
        {
            sendThread = new Thread(sendFile);//开启发送文件线程  
            sendThread.Start();
        }


        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("发送失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                labelInfo.Text = "发送失败!";
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    buttonSend.Enabled = true;
                }
            }
        }
        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[] { '/' });
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void labelRecDir_Click(object sender, EventArgs e)
        {

        }

        SerialPort BluetoothConnection = new SerialPort();
        int length = 20;
        string BlueToothReceivedData = "";
        private void button3_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 send_Click(object sender, EventArgs e)
        {
            BluetoothClient cli = new BluetoothClient();
            BluetoothEndPoint ep = null;
            try
            {
              
                // [注意2]:要注意MAC地址中字节的对应关系,直接来看顺序是相反的,例如
                // 如下对应的MAC地址为——12:34:56:78:9a:bc
                ep = new BluetoothEndPoint(sendAddress, BluetoothService.SerialPort);
                cli.Connect(ep); // 连接蓝牙

                if (cli.Connected)
                {
                    MessageBox.Show("端口1已打开");
                    Stream peerStream = cli.GetStream();
                    peerStream.WriteByte(0xBB); // 发送开门指令
                }
                else {
                    MessageBox.Show("端口1没打开");
                }
            }
            catch 
            {
                Console.WriteLine("123123");
                Console.ReadLine();
            }
            finally
            {
                if (cli != null)
                {
                    // [注意3]:要延迟一定时间(例如1000毫秒)
                    //避免因连接后又迅速断开而导致蓝牙进入异常(傻逼)状态
                    Thread.Sleep(1000);
                    cli.Close();
                }
            }
            ///
            byte[] head = new byte[8] { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 };//随便写的一组数据,里面的数据无意
           
            try
            {
                BluetoothConnection.PortName = comboBox.Text;
                BluetoothConnection.BaudRate = 9600;
                BluetoothConnection.Open();//打开蓝牙串口
                if (BluetoothConnection.IsOpen) { BlueToothReceivedData = " d1_on";
                    MessageBox.Show("端口已打开");
                    BlueToothReceivedData = " d1_on";
                    //BluetoothConnection.Write(head, 0, head.Length);
                    BluetoothConnection.Write("12323");
                    Thread.Sleep(1000);
                    MessageBox.Show("完成");
                }
                //BluetoothConnection.WriteLine(BlueToothReceivedData);
                //byte[] head = new byte[8] { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 };//随便写的一组数据,里面的数据无意义
                BluetoothConnection.Write(head, 0, head.Length);

            }
            catch
            {
                label1.Text = "发送失败"; ;
            }

           
        }

        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]);//"+="表示接收数据事件发生时,触发"+="后面的语句
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (sendThread != null)
            {
                sendThread.Abort();
            }
            if (listenThread != null)
            {
                listenThread.Abort();
            }
            if (listener != null && listener.IsListening)
            {
                listener.Stop();
            }
        }
    }
}

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值