#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <signal.h>
#include <termios.h>
#include <sys/poll.h>
#include <sys/param.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/rfcomm.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/rfcomm.h>
int main(int argc, char **argv) {
orther_server();
while(1){
usleep(1000);
}
return 0;
}
void baswap(bdaddr_t *dst, const bdaddr_t *src) {
unsigned char * d = (unsigned char *)dst;
const unsigned char *s = (const unsigned char *)src;
int i;
for (i = 0; i < 6; i++) d[i] = s[5 - i];
}
int ba2str(const bdaddr_t *ba, char *str) {
uint8_t b[6];
baswap((bdaddr_t *)b, ba);
return sprintf(str, "%2.2X:%2.2X:%2.2X:%2.2X:%2.2X:%2.2X", b[0], b[1], b[2], b[3], b[4], b[5]);
}
int orther_server()
{
struct sockaddr_rc loc_addr = { 0 }, rem_addr = { 0 };
char buf[1024] = { 0 };
int s, client, bytes_read;
int opt = sizeof(rem_addr);
// allocate socket
s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
// bind socket to port 1 of the first available
// local bluetooth adapter
loc_addr.rc_family = AF_BLUETOOTH;
loc_addr.rc_bdaddr = *BDADDR_ANY;
loc_addr.rc_channel = (uint8_t) 1;//这里的通道就是SPP的通道
bind(s, (struct sockaddr *)&loc_addr, sizeof(loc_addr));
// put socket into listening mode
listen(s, 1);
printf("orther_server listen success\n");
// accept one connection
//这里accept没有做并发处理,只能连接要给设,后续可自行扩展
client = accept(s, (struct sockaddr *)&rem_addr, &opt);
ba2str( &rem_addr.rc_bdaddr, buf );
printf("client connected success\n");
fprintf(stderr, "accepted connection from %s\n", buf);
//这里循环读数据也没有做线程处理,一直在读,应该放到线程种,同样的写数据一样的道理
for(;;)
{
memset(buf, 0, sizeof(buf));
// read data from the client
bytes_read = read(client, buf, sizeof(buf));
if( bytes_read > 0 ) {
printf("received [%s]\n", buf);
}
}
// close connection
close(client);
close(s);
return 0;
}
- 1
- 2
- 3
前往页