如何用C#在PC上查找连接蓝牙设备并实现数据传输
概述
在PC端用.NET开发一个蓝牙下载的程序。实现在PC上查找周围的蓝牙设备(主要是手机),并将PC上的文件通过蓝牙传输到手机上。目前我采用的是OpenNETCF.Net.Bluetooth,能够正常发现周围的蓝牙设备,手机也能够正常进行蓝牙连接并接收文件。
代码实现
1、查找周围蓝牙设备
BluetoothClientbc=newBluetoothClient(); BluetoothDeviceInfo[]bdi; bdi=bc.DiscoverDevices(10);//查找周围最多10个蓝牙设备 if(bdi.Length==0) { this.ShowErrMsg("请确认您的蓝牙已开启!"); return; }
2、打开数据流
#regionOBEXOpenStream publicboolOBEXOpenStream(stringBTMAC) { //serialportUUID Guidspguid=OpenNETCF.Net.Bluetooth.BluetoothService.ObexObjectPush; OpenNETCF.Net.BluetoothAddressbtaddress=OpenNETCF.Net.BluetoothAddress.Parse(BTMAC); client=newOpenNETCF.Net.Sockets.BluetoothClient(); //defineendpoint OpenNETCF.Net.BluetoothEndPointendpoint=newOpenNETCF.Net.BluetoothEndPoint(btaddress,spguid); try { //opensocket client.Connect(endpoint); } catch { //unabletoconnect(servernotlisteningonspguid) returnfalse; } //connectsocket stream=client.GetStream(); returntrue; } #endregion
3、配对连接
privateboolOBEXConnect() { //sendclientrequest byte[]ConnectPacket=newbyte[7]; ConnectPacket[0]=0x80;//Connect ConnectPacket[1]=0x00;//PacketlengthHiByte ConnectPacket[2]=0x07;//PacketlengthLoByte ConnectPacket[3]=0x10;//Obexv1 ConnectPacket[4]=0x00;//noflags ConnectPacket[5]=0x20;//8kmaxpacketsizeHiByte ConnectPacket[6]=0x00;//8kmaxpacketsizeLoByte stream.Write(ConnectPacket,0,ConnectPacket.Length); //listenforserverresponse byte[]ReceiveBufferA=newbyte[3]; stream.Read(ReceiveBufferA,0,3); if(ReceiveBufferA[0]==160)//0xa0 { //success,decoderestofpacket intplength=(0xff*ReceiveBufferA[1])+ReceiveBufferA[2];//lengthofpacketis... //listenforrestofpacket byte[]ReceiveBufferB=newbyte[plength-3]; stream.Read(ReceiveBufferB,0,plength-3); intobver=ReceiveBufferB[0];//serverobexversion(16=v1.0) intcflags=ReceiveBufferB[1];//connectflags intmaxpack=(0xff*ReceiveBufferB[2])+ReceiveBufferB[3];//maxpacketsize returntrue; } else { returnfalse; } }
4、发送文本内容
//sendclientrequest,startput stringtName="BRT优惠卷.txt"; stringtType=""; stringtFileContent="优惠卷内容:"+this.txtContent.Text.Trim(); intresult=OBEXRequest("PUT",tName,tType,tFileContent); if(result==160) { SendSuccess=true; }
完整代码
usingSystem; usingSystem.Data; usingSystem.Configuration; usingSystem.Web; usingSystem.Web.Security; usingSystem.Web.UI; usingSystem.Web.UI.WebControls; usingSystem.Web.UI.WebControls.WebParts; usingSystem.Web.UI.HtmlControls; usingSystem.Net.Sockets; usingOpenNETCF; usingOpenNETCF.Net; usingOpenNETCF.Net.Bluetooth; usingOpenNETCF.Net.Sockets; publicpartialclass_Default:System.Web.UI.Page { //Streamstream; NetworkStreamstream; OpenNETCF.Net.Sockets.BluetoothClientclient; protectedvoidPage_Load(objectsender,EventArgse) { } #regionShowErrMsg privatevoidShowErrMsg(stringerr) { stringstr; str=""; str+="alert('"+err+"')"; str+=""; this.RegisterStartupScript("",str); } #endregion protectedvoidbtnSend_Click(objectsender,EventArgse) { if(this.txtContent.Text.Trim()==string.Empty) { this.ShowErrMsg("请输入发送内容!"); return; } BluetoothClientbc=newBluetoothClient(); BluetoothDeviceInfo[]bdi; bdi=bc.DiscoverDevices(10);//查找周围最多10个蓝牙设备 if(bdi.Length==0) { this.ShowErrMsg("请确认您的蓝牙已开启!"); return; } boolSendSuccess=false; try { foreach(BluetoothDeviceInfobdinbdi) { if(OBEXOpenStream(bd.DeviceID.ToString())) { if(OBEXConnect()) { //sendclientrequest,startput stringtName="BRT优惠卷.txt"; stringtType=""; stringtFileContent="优惠卷内容:"+this.txtContent.Text.Trim(); intresult=OBEXRequest("PUT",tName,tType,tFileContent); if(result==160) { SendSuccess=true; } } OBEXCloseStream(); } else { this.ShowErrMsg("连接失败!"+bd.DeviceName.ToString()); } } if(SendSuccess) { this.ShowErrMsg("发送成功,谢谢使用!"); } } finally { OBEXCloseStream(); } } #regionOBEXOpenStream publicboolOBEXOpenStream(stringBTMAC) { //serialportUUID Guidspguid=OpenNETCF.Net.Bluetooth.BluetoothService.ObexObjectPush; OpenNETCF.Net.BluetoothAddressbtaddress=OpenNETCF.Net.BluetoothAddress.Parse(BTMAC); client=newOpenNETCF.Net.Sockets.BluetoothClient(); //defineendpoint OpenNETCF.Net.BluetoothEndPointendpoint=newOpenNETCF.Net.BluetoothEndPoint(btaddress,spguid); try { //opensocket client.Connect(endpoint); } catch { //unabletoconnect(servernotlisteningonspguid) returnfalse; } //connectsocket stream=client.GetStream(); returntrue; } #endregion #regionOBEXCloseStream privatevoidOBEXCloseStream() { if(stream!=null) { stream.Close(); } if(client!=null) { client.Close(); } } #endregion #regionOBEXConnect privateboolOBEXConnect() { //sendclientrequest byte[]ConnectPacket=newbyte[7]; ConnectPacket[0]=0x80;//Connect ConnectPacket[1]=0x00;//PacketlengthHiByte ConnectPacket[2]=0x07;//PacketlengthLoByte ConnectPacket[3]=0x10;//Obexv1 ConnectPacket[4]=0x00;//noflags ConnectPacket[5]=0x20;//8kmaxpacketsizeHiByte ConnectPacket[6]=0x00;//8kmaxpacketsizeLoByte stream.Write(ConnectPacket,0,ConnectPacket.Length); //listenforserverresponse byte[]ReceiveBufferA=newbyte[3]; stream.Read(ReceiveBufferA,0,3); if(ReceiveBufferA[0]==160)//0xa0 { //success,decoderestofpacket intplength=(0xff*ReceiveBufferA[1])+ReceiveBufferA[2];//lengthofpacketis... //listenforrestofpacket byte[]ReceiveBufferB=newbyte[plength-3]; stream.Read(ReceiveBufferB,0,plength-3); intobver=ReceiveBufferB[0];//serverobexversion(16=v1.0) intcflags=ReceiveBufferB[1];//connectflags intmaxpack=(0xff*ReceiveBufferB[2])+ReceiveBufferB[3];//maxpacketsize returntrue; } else { returnfalse; } } #endregion #regionOBEXRequest privateintOBEXRequest(stringtReqType,stringtName,stringtType,stringtFileContent) { //sendclientrequest inti; intoffset; intpacketsize; bytereqtype=0x82; inttTypeLen=0x03; inttypeheadsize; inttypesizeHi=0x00; inttypesizeLo=0x03; //tName="contact.vcf"; //tType="text/x-vCard"; //tFileContent="BEGIN:VCARD\r\nVERSION:2.1\r\nN:;aardvark\r\nFN:aardvark\r\nEND:VCARD\r\n"; if(tReqType=="GET") { reqtype=0x83;//131GET-Final } if(tReqType=="PUT") { reqtype=0x82;//130PUT-Final } packetsize=3; //NameHeader inttNameLength=tName.Length; intnameheadsize=(3+(tNameLength*2)+2); intnamesizeHi=(nameheadsize&0xff00)/0xff; intnamesizeLo=nameheadsize&0x00ff; packetsize=packetsize+nameheadsize; if(tType!="") { //TypeHeader tTypeLen=tType.Length; typeheadsize=3+tTypeLen+1; typesizeHi=(typeheadsize&0xff00)/0xff; typesizeLo=typeheadsize&0x00ff; packetsize=packetsize+typeheadsize; } //Body intfileLen=System.Text.Encoding.Default.GetBytes(tFileContent).Length;//tFileContent.Length; intfileheadsize=3+fileLen; intfilesizeHi=(fileheadsize&0xff00)/0xff;; intfilesizeLo=fileheadsize&0x00ff;; packetsize=packetsize+fileheadsize; intpacketsizeHi=(packetsize&0xff00)/0xff; intpacketsizeLo=packetsize&0x00ff; byte[]tSendByte=newbyte[packetsize]; //PUT-finalHeader tSendByte[0]=reqtype;//Requesttypee.g.PUT-final130 tSendByte[1]=Convert.ToByte(packetsizeHi);//PacketlengthHi tSendByte[2]=Convert.ToByte(packetsizeLo);//PacketlengthLo offset=2; //NameHeader tSendByte[offset+1]=0x01;//HIforNameheader tSendByte[offset+2]=Convert.ToByte(namesizeHi);//LengthofNameheader(2bytesperchar) tSendByte[offset+3]=Convert.ToByte(namesizeLo);//LengthofNameheader(2bytesperchar) //Name+\n\ninunicode byte[]tNameU=System.Text.Encoding.BigEndianUnicode.GetBytes(tName); tNameU.CopyTo(tSendByte,offset+4); offset=offset+3+(tNameLength*2); tSendByte[offset+1]=0x00;//nullterm tSendByte[offset+2]=0x00;//nullterm offset=offset+2; if(tType!="") { //TypeHeader tSendByte[offset+1]=0x42;//HIforTypeHeader66 tSendByte[offset+2]=Convert.ToByte(typesizeHi);//LengthofTypeHeader tSendByte[offset+3]=Convert.ToByte(typesizeLo);//LengthofTypeHeader for(i=0;i<=(tTypeLen-1);i++) { tSendByte[offset+4+i]=Convert.ToByte(Convert.ToChar(tType.Substring(i,1))); } tSendByte[offset+3+tTypeLen+1]=0x00;//nullterminator offset=offset+3+tTypeLen+1; } //Body tSendByte[offset+1]=0x49;//HIEndofBody73 tSendByte[offset+2]=Convert.ToByte(filesizeHi);// tSendByte[offset+3]=Convert.ToByte(filesizeLo);//1kpayload+3forHIheader //for(i=0;i<=(fileLen-1);i++) //{ //tSendByte[offset+4+i]=Convert.ToByte(tFileContent.Substring(i,1));//Convert.ToByte(Convert.ToChar(tFileContent.Substring(i,1))); //} byte[]bfile=System.Text.Encoding.Default.GetBytes(tFileContent); for(i=0;i<=bfile.Length-1;i++) { tSendByte[offset+4+i]=bfile[i]; } //tSendByte[offset+4+fileLen]=0x00;//nullterminator offset=offset+3+fileLen; stream.Write(tSendByte,0,tSendByte.Length); //listenforserverresponse //TODO:canhanghereforeverwaitingresponse... boolx=stream.DataAvailable;//changedbluetoothclient-publicNetworkStreamGetStream() byte[]tArray4=newbyte[3]; stream.Read(tArray4,0,3); x=stream.DataAvailable; if(tArray4[0]==160)//0xa0 { intplength=(tArray4[1]*256)+tArray4[2]-3; byte[]tArray5=newbyte[plength]; if(plength>0) { stream.Read(tArray5,0,plength); //TODO:datainreturnedpackettodealwith } return160; } if(tArray4[0]==197)//0xc5Methodnotallowed { return197; } if(tArray4[0]==192)//0xc0BadRequest { return192; } return0; } #endregion }
以上就是如何用C#在PC上查找连接蓝牙设备并实现数据传输的详细内容,更多关于c#蓝牙传输的资料请关注毛票票其它相关文章!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。