赞
踩
蓝牙的基本功能无非就是配对(后面会阐述),基于OPUSH协议的传输文件(后面会讲),向蓝牙播放音频(以后会讲),基于rfcomm的通信,拨号上网,ftp等。通过对bluez的深入学习,已基本上实现了在linux系统下的基本功能,后面还会介绍如何修改蓝牙的配置信息等技术。
这节就简单介绍下基于rfcomm的通信编程的服务器端的实现。其实就是socket编程,与我们不同的是IP变成了MAC,端口号变成了Channel。
在编译的时候记得指定bluez的includes和lbluetooth哦。
配对成功后才能使用!!!!!!!!!!!!!!!!!!
- 1 #include <stdio.h>
- 2 #include <stdlib.h>
- 3 #include <unistd.h>
- 4 #include <sys/socket.h>
- 5 #include <bluetooth/bluetooth.h>
- 6 #include <bluetooth/rfcomm.h>
- 7
- 8 int main (int argc,char **argv)
- 9 {
- 10 struct sockaddr_rc loc_addr ={0},rem_addr={0};
- 11 char buf[1024] ={0};//,*addr;
- 12 int s,client, bytes_read,result;
- 13 int opt = sizeof(rem_addr);
- 14 /*Fir--creat socket */
- 15 printf("Creating socket...\n");
- 16 s =socket(PF_BLUETOOTH,SOCK_STREAM,BTPROTO_RFCOMM);
- 17 if(s<0)
- 18 {
- 19 perror("create socket error");
- 20 exit(1);
- 21 }
- 22 else
- 23 {
- 24 printf("success!\n");
- 25 }
- 26
- 27
- 28 loc_addr.rc_family=AF_BLUETOOTH;
- 29 loc_addr.rc_bdaddr=*BDADDR_ANY;
- 30 loc_addr.rc_channel=(uint8_t)1;
- 31
- 32 /*bind socket*/
- 33 printf("zkwang******Binding socket...\n");
- 34 result=bind(s,(struct sockaddr *)&loc_addr, sizeof(loc_addr));
- 35 if(result<0)
- 36 {
- 37 perror("bind socket error:");
- 38 exit(1);
- 39 }
- 40 else
- 41 {
- 42 printf("zkwang******success!\n");
- 43
- 44 }
- 45
- 46 /*Listen*/
- 47 printf("Listen... \n");
- 48 result=listen(s,5);
- 49 if(result<0)
- 50 {
- 51 printf("error:%d\n:",result);
- 52 perror("listen error:");
- 53 exit(1);
- 54 }
- 55 else
- 56 {
- 57 printf("requested!\n");
- 58 }
- 59
- 60 /*Accept*/
- 61 printf("Accepting...\n");
- 62 client= accept(s,(struct sockaddr *)&rem_addr,&opt);
- 63 if(client<0)
- 64 {
- 65 perror("accept error\n");
- 66 exit(1);
- 67 }
- 68 else
- 69 {
- 70 printf("OK!\n");
- 71 }
- 72
- 73 ba2str(&rem_addr.rc_bdaddr,buf);
- 74
- 75 printf("accepted connection from %s \n",buf);
- 76 memset(buf,0,sizeof(buf));
- 77
- 78 while(1)
- 79 {
- 80 bytes_read = read(client,buf,sizeof(buf));
- 81 if(bytes_read>0){
- 82 printf("Received:%s\n",buf);
- 83 if(strcmp(buf,"goodbye")==0)
- 84 {
- 85 printf("Client is down!!");
- 86 exit(1);
- 87 }
- 88 memset(buf,0,bytes_read);
- 89 }
- 90 }
- 91 close(client);
- 92 close(s);
- 93 return 0 ;
- 94 }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。