求高手看下,C#蓝牙

u010878933 2013-10-25 05:39:36
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;

using InTheHand.Windows.Forms;
using InTheHand.Net;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Sockets;

using System.Threading;
using System.Runtime.InteropServices;

using System.Net;
using System.IO;

namespace bluetooth
{
public partial class Form1 : Form
{
BluetoothRadio radio = null;//蓝牙适配器
string sendFileName = null;//发送文件名
BluetoothAddress sendAddress = null;//发送目的地址
ObexListener listener = null;//监听器
string recDir = null;//接受文件存放目录

BluetoothClient bluetoothClient;
BluetoothListener bluetoothListener;
Thread listenThread;
bool isConnected;
NetworkStream peerStream;

public Form1()
{
InitializeComponent();
radio = BluetoothRadio.PrimaryRadio;//获取当前PC的蓝牙适配器
CheckForIllegalCrossThreadCalls = false;//不检查跨线程调用
if (radio == null)//检查该电脑蓝牙是否可用
{
MessageBox.Show("这个电脑蓝牙不可用!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
recDir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
// labelRecDir1.Text = recDir;
}

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;//获取选择的远程蓝牙地址
label1.Text = "地址:" + sendAddress.ToString() + "设备名:" + dialog.SelectedDevice.DeviceName;
listenThread = new Thread(ReceiveData);
listenThread.Start();
}
}


private void ReceiveData()
{
try
{
// textBox1.Text = sendAddress.ToString();
Guid mGUID = Guid.Parse("e0cbf06c-cd8b-4647-bb8a-263b43f0f974"); // radio.LocalAddress sendAddress.ToString()
bluetoothListener = new BluetoothListener(mGUID);
bluetoothListener.Start();

label3.Text = bluetoothListener.ServiceName.ToString();
bluetoothClient = bluetoothListener.AcceptBluetoothClient();
label2.Text = "3";
isConnected = true;
}
catch (Exception ex)
{
label2.Text = ex.Message.ToString();
isConnected = false;
}
while (isConnected)
{

string receive = string.Empty;
if (bluetoothClient == null)
{
break;
}
try
{
peerStream = bluetoothClient.GetStream();
byte[] buffer = new byte[6];
peerStream.Read(buffer, 0, 6);
receive = Encoding.UTF8.GetString(buffer).ToString();
}
catch (System.Exception)
{
}
Thread.Sleep(100);
}
}

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


}
}
...全文
582 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
AKQJX 2016-05-18
  • 打赏
  • 举报
回复
同楼上,119131429@qq.com 项目要做蓝牙一对多连接,目前还没上手
jiantonger 2016-04-05
  • 打赏
  • 举报
回复
楼主你好,不知道你问题解决了吗?能发我一份吗?jiantonger@163.com
abbyyuanna 2016-01-04
  • 打赏
  • 举报
回复
引用 3 楼 ssnqqdx 的回复:
我最近也开发了这个蓝牙通讯 的,代码结构跟你的很类似,没有问题,你参考下

  protected BluetoothDeviceInfo device = null;
        protected BluetoothClient client = null;
        Stream peerStream = null;
        ///蓝牙名
        string blueName = BGLms.Handset.Code_JM.Configuration.XmlConfiguration.Instance.BlueName;
        ///蓝牙密码
        string bluePwd = BGLms.Handset.Code_JM.Configuration.XmlConfiguration.Instance.BluePwd;
 /// <summary>
        /// Conn连接蓝牙
        /// </summary>
        public void loadConnectService()
        {
            try
            {
                if (client == null)
                    client = new BluetoothClient();
                BluetoothDeviceInfo[] devices = client.DiscoverDevices();
                //MessageBox.Show(devices.Length.ToString());

                foreach (BluetoothDeviceInfo d in devices)
                {
                    if (d.DeviceName == blueName)
                    {
                        device = d;
                        break;
                    }
                }
                //device = devices[0];
                Thread.Sleep(400);
                if (!device.Connected)
                {
                    if (device == null) { MessageBox.Show("device is null"); return; }
                    //MessageBox.Show("device.DeviceName:" + device.DeviceName);
                    //MessageBox.Show("device.DeviceAddress:" + device.DeviceAddress);
                    client.SetPin(device.DeviceAddress, bluePwd);  //密码 
                    client.Connect(device.DeviceAddress, BluetoothService.SerialPort);
                }
            }
            catch (Exception ex)
            {
                if (peerStream != null)
                {
                    //peerStream.Close();
                    peerStream.Dispose();
                }
                if (client != null)
                {
                    client.Close();
                    client.Dispose();
                }
                MessageBox.Show("蓝牙连接出错,请重新获取:" + ex.Message);
                loadCount = 0;
                return;
            }
        }

 /// <summary>
        /// 获取数据
        /// </summary>
        private void GetMac()
        {
            StringBuilder resultdata = new StringBuilder();
            //string errorMsg = "";
            try
            {
                int I = 0;
                Thread.Sleep(500);
                if (!client.Connected)
                {
                    //MessageBox.Show("device不为null:"+evice.Connected.ToString());
                    // MessageBox.Show("device不为null:" + device.DeviceName);
                    //MessageBox.Show(client.Connected.ToString());
                    try { BluetoothAddress blueAddress = device.DeviceAddress; }
                    catch
                    {
                        BluetoothDeviceInfo[] devices = client.DiscoverDevices();
                        foreach (BluetoothDeviceInfo d in devices)
                        {
                            if (d.DeviceName == blueName)
                            {
                                device = d;
                                break;
                            }
                        }
                    }
                    client.SetPin(device.DeviceAddress, bluePwd);  //密码 
                    client.Connect(device.DeviceAddress, BluetoothService.SerialPort);
                }

                if (peerStream == null)
                    peerStream = client.GetStream();
                #region MyRegion
                while (true)
                {
                    byte[] buffer = new byte[4096];
                    // Read Data
                    if (peerStream.CanRead)
                    {
                        peerStream.Read(buffer, 0, 4096);
                        // Convert Data to String
                        string data = System.Text.ASCIIEncoding.ASCII.GetString(buffer, 0, 4096);
                        data = data.Substring(1, data.Length - 1);
                        string[] arraystr = data.Split('=');
                        if (arraystr.Length < 512) //判断是不否读完
                        {
                            for (int i = arraystr[arraystr.Length - 2].Length - 1; i >= 0; i--)
                            {
                                resultdata.Append(arraystr[arraystr.Length - 2][i].ToString());
                            }
                            break;
                        }
                    }
                    if (I > int.MaxValue)
                    {
                        break;
                    }
                    I++;
                }
                #endregion
                resultdata.ToString();
            }
            catch (Exception ex)
            {
                if (peerStream != null)
                {
                    peerStream.Close();
                    peerStream.Dispose();
                }
                if (client != null)
                {
                    client.Close();
                    client.Dispose();
                }
                MessageBox.Show("蓝牙为连接失败,重新获取!" + ex.Message);
                loadCount = 0;
                // loadConnectService();
                return;
            }
}

我想问问如何获取蓝牙信号强大 急!
ssnqqdx 2015-07-03
  • 打赏
  • 举报
回复
我最近也开发了这个蓝牙通讯 的,代码结构跟你的很类似,没有问题,你参考下

  protected BluetoothDeviceInfo device = null;
        protected BluetoothClient client = null;
        Stream peerStream = null;
        ///蓝牙名
        string blueName = BGLms.Handset.Code_JM.Configuration.XmlConfiguration.Instance.BlueName;
        ///蓝牙密码
        string bluePwd = BGLms.Handset.Code_JM.Configuration.XmlConfiguration.Instance.BluePwd;
 /// <summary>
        /// Conn连接蓝牙
        /// </summary>
        public void loadConnectService()
        {
            try
            {
                if (client == null)
                    client = new BluetoothClient();
                BluetoothDeviceInfo[] devices = client.DiscoverDevices();
                //MessageBox.Show(devices.Length.ToString());

                foreach (BluetoothDeviceInfo d in devices)
                {
                    if (d.DeviceName == blueName)
                    {
                        device = d;
                        break;
                    }
                }
                //device = devices[0];
                Thread.Sleep(400);
                if (!device.Connected)
                {
                    if (device == null) { MessageBox.Show("device is null"); return; }
                    //MessageBox.Show("device.DeviceName:" + device.DeviceName);
                    //MessageBox.Show("device.DeviceAddress:" + device.DeviceAddress);
                    client.SetPin(device.DeviceAddress, bluePwd);  //密码 
                    client.Connect(device.DeviceAddress, BluetoothService.SerialPort);
                }
            }
            catch (Exception ex)
            {
                if (peerStream != null)
                {
                    //peerStream.Close();
                    peerStream.Dispose();
                }
                if (client != null)
                {
                    client.Close();
                    client.Dispose();
                }
                MessageBox.Show("蓝牙连接出错,请重新获取:" + ex.Message);
                loadCount = 0;
                return;
            }
        }

 /// <summary>
        /// 获取数据
        /// </summary>
        private void GetMac()
        {
            StringBuilder resultdata = new StringBuilder();
            //string errorMsg = "";
            try
            {
                int I = 0;
                Thread.Sleep(500);
                if (!client.Connected)
                {
                    //MessageBox.Show("device不为null:"+evice.Connected.ToString());
                    // MessageBox.Show("device不为null:" + device.DeviceName);
                    //MessageBox.Show(client.Connected.ToString());
                    try { BluetoothAddress blueAddress = device.DeviceAddress; }
                    catch
                    {
                        BluetoothDeviceInfo[] devices = client.DiscoverDevices();
                        foreach (BluetoothDeviceInfo d in devices)
                        {
                            if (d.DeviceName == blueName)
                            {
                                device = d;
                                break;
                            }
                        }
                    }
                    client.SetPin(device.DeviceAddress, bluePwd);  //密码 
                    client.Connect(device.DeviceAddress, BluetoothService.SerialPort);
                }

                if (peerStream == null)
                    peerStream = client.GetStream();
                #region MyRegion
                while (true)
                {
                    byte[] buffer = new byte[4096];
                    // Read Data
                    if (peerStream.CanRead)
                    {
                        peerStream.Read(buffer, 0, 4096);
                        // Convert Data to String
                        string data = System.Text.ASCIIEncoding.ASCII.GetString(buffer, 0, 4096);
                        data = data.Substring(1, data.Length - 1);
                        string[] arraystr = data.Split('=');
                        if (arraystr.Length < 512) //判断是不否读完
                        {
                            for (int i = arraystr[arraystr.Length - 2].Length - 1; i >= 0; i--)
                            {
                                resultdata.Append(arraystr[arraystr.Length - 2][i].ToString());
                            }
                            break;
                        }
                    }
                    if (I > int.MaxValue)
                    {
                        break;
                    }
                    I++;
                }
                #endregion
                resultdata.ToString();
            }
            catch (Exception ex)
            {
                if (peerStream != null)
                {
                    peerStream.Close();
                    peerStream.Dispose();
                }
                if (client != null)
                {
                    client.Close();
                    client.Dispose();
                }
                MessageBox.Show("蓝牙为连接失败,重新获取!" + ex.Message);
                loadCount = 0;
                // loadConnectService();
                return;
            }
}

u010878933 2013-10-25
  • 打赏
  • 举报
回复
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;

using InTheHand.Windows.Forms;
using InTheHand.Net;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Sockets;

using System.Threading;
using System.Runtime.InteropServices;

using System.Net;
using System.IO;

namespace bluetooth
{
    public partial class Form1 : Form
    {
        BluetoothRadio radio = null;//蓝牙适配器  
        string sendFileName = null;//发送文件名  
        BluetoothAddress sendAddress = null;//发送目的地址  
        ObexListener listener = null;//监听器  
        string recDir = null;//接受文件存放目录  

        BluetoothClient bluetoothClient;
        BluetoothListener bluetoothListener;
        Thread listenThread;
        bool isConnected;
        NetworkStream peerStream;

        public Form1()
        {
            InitializeComponent();
            radio = BluetoothRadio.PrimaryRadio;//获取当前PC的蓝牙适配器  
            CheckForIllegalCrossThreadCalls = false;//不检查跨线程调用  
            if (radio == null)//检查该电脑蓝牙是否可用  
            {
                MessageBox.Show("这个电脑蓝牙不可用!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            recDir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
           // labelRecDir1.Text = recDir;
        }

        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;//获取选择的远程蓝牙地址  
                label1.Text = "地址:" + sendAddress.ToString() + "设备名:" + dialog.SelectedDevice.DeviceName;
                listenThread = new Thread(ReceiveData);
                listenThread.Start();
            }
        }
  

        private void ReceiveData()
        {
            try
            {
              //  textBox1.Text = sendAddress.ToString();
                Guid mGUID = Guid.Parse("e0cbf06c-cd8b-4647-bb8a-263b43f0f974"); //  radio.LocalAddress      sendAddress.ToString()
                bluetoothListener = new BluetoothListener(mGUID); 
                bluetoothListener.Start();    
     //在这里程序就不动了
                label3.Text = bluetoothListener.ServiceName.ToString();
                bluetoothClient = bluetoothListener.AcceptBluetoothClient();
                label2.Text = "3";   
                isConnected = true;   
            }
            catch (Exception ex)
            {
                label2.Text = ex.Message.ToString();
                isConnected = false;
            }
            while (isConnected)
            {
            
                string receive = string.Empty;
                if (bluetoothClient == null)
                {
                    break;
                }
                try
                {
                    peerStream = bluetoothClient.GetStream();
                    byte[] buffer = new byte[6];
                    peerStream.Read(buffer, 0, 6);
                    receive = Encoding.UTF8.GetString(buffer).ToString();
                }
                catch (System.Exception)
                {
                }
                Thread.Sleep(100);
            }
        }

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


    }
}
u010878933 2013-10-25
  • 打赏
  • 举报
回复
在线等

110,571

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧