欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Windows系统中使用C#编写蓝牙通信程序的简单实例

程序员文章站 2022-11-23 22:55:08
现在很多电脑提供了蓝牙支持,很多笔记本网卡也集成了蓝牙功能,也可以采用usb蓝牙方便的连接手机等蓝牙设备进行通信。 操作蓝牙要使用类库inthehand.net.pers...

现在很多电脑提供了蓝牙支持,很多笔记本网卡也集成了蓝牙功能,也可以采用usb蓝牙方便的连接手机等蓝牙设备进行通信。
操作蓝牙要使用类库inthehand.net.personal
首先在项目中引用该类库;

static void main(string[] args) 
{ 
  bluetoothradio bluetoothradio = bluetoothradio.primaryradio; 
  if (bluetoothradio == null) 
  { 
  console.writeline("没有找到本机蓝牙设备!"); 
  } 
  else 
  { 
  console.writeline("classofdevice: " + bluetoothradio.classofdevice); 
  console.writeline("hardwarestatus: " + bluetoothradio.hardwarestatus); 
  console.writeline("hcirevision: " + bluetoothradio.hcirevision); 
  console.writeline("hciversion: " + bluetoothradio.hciversion); 
  console.writeline("lmpsubversion: " + bluetoothradio.lmpsubversion); 
  console.writeline("lmpversion: " + bluetoothradio.lmpversion); 
  console.writeline("localaddress: " + bluetoothradio.localaddress); 
  console.writeline("manufacturer: " + bluetoothradio.manufacturer); 
  console.writeline("mode: " + bluetoothradio.mode); 
  console.writeline("name: " + bluetoothradio.name); 
  console.writeline("remote:" + bluetoothradio.remote); 
  console.writeline("softwaremanufacturer: " + bluetoothradio.softwaremanufacturer); 
  console.writeline("stackfactory: " + bluetoothradio.stackfactory); 
  } 
  console.readkey(); 
} 

 如果pc插入了蓝牙适配器,便会显示蓝牙相关信息:

Windows系统中使用C#编写蓝牙通信程序的简单实例

 然后我们就要利用蓝牙收发文件了:
前提是蓝牙设备(如手机)已经和pc配对了

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); 
    labelrecdir.text = recdir; 
  } 
 
  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 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 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 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 form1_formclosed(object sender, formclosedeventargs e) 
  { 
    if (sendthread != null) 
    { 
      sendthread.abort(); 
    } 
    if (listenthread != null) 
    { 
      listenthread.abort(); 
    } 
    if (listener != null && listener.islistening) 
    { 
      listener.stop(); 
    } 
  } 
} 

程序界面:

Windows系统中使用C#编写蓝牙通信程序的简单实例

selectbluetoothdevicedialog是一个inthehand.net.personal提供的窗体,用于选择蓝牙设备:

Windows系统中使用C#编写蓝牙通信程序的简单实例

从手机往电脑发送文件需要在电脑上开启监听obexlistener,才能收到文件。

Windows系统中使用C#编写蓝牙通信程序的简单实例

核心代码:

bluetoothradio radio = null;//蓝牙适配器 
string sendfilename = null;//发送文件名 
bluetoothaddress sendaddress = null;//发送目的地址 
obexlistener listener = null;//监听器 
string recdir = null;//接受文件存放目录 
thread listenthread, sendthread;//发送/接收线程 
 
radio = bluetoothradio.primaryradio;//获取当前pc的蓝牙适配器 
 
//关于蓝牙设备选择对话框 
selectbluetoothdevicedialog dialog = new selectbluetoothdevicedialog(); 
dialog.showremembered = true;//显示已经记住的蓝牙设备 
dialog.showauthenticated = true;//显示认证过的蓝牙设备 
dialog.showunknown = true;//显示位置蓝牙设备 
sendaddress = dialog.selecteddevice.deviceaddress;//获取选择的远程蓝牙地址 
 
//发送文件操作 
obexwebrequest request = new obexwebrequest(sendaddress, path.getfilename(sendfilename));//创建网络请求 
webresponse response = null; 
request.readfile(sendfilename);//发送文件 
response = request.getresponse();//获取回应 
response.close(); 
 
//接收文件 
radio.mode = radiomode.discoverable;//设置本地蓝牙可被检测 
listener = new obexlistener(obextransport.bluetooth);//创建监听 
listener.start(); 
listener.stop(); 
 
obexlistenercontext context = null; 
obexlistenerrequest request = null; 
context = listener.getcontext();//获取监听上下文 
request = context.request;//获取请求 
string uristring = uri.unescapedatastring(request.rawurl);//将uri转换成字符串 
string recfilename = recdir + uristring; 
request.writefile(recfilename);//接收文件 
labelrecinfo.text = "收到文件" + uristring.trimstart(new char[] { '/' } 

ps:关于inthehand.net.personal
inthehand.net.personal.dll来源于32feet.net。
32feet.net是shared-source的项目,支持cf.net 2.0以及桌面版本.net framework,提供短距离领域(personal area networking technologie)的通信功能,支持bluetooth,infrared(irda)红外等. 想了解更多的信息可以参考其 官方主页,其项目的安装包和源码是放在微软的开源工程网站codeplex上面的,作为.net开发人员我们必须要上的网站就是codeplex~