sockets - 带有raspberrypi的android设备的蓝牙通信-连接被拒绝时出现错误
问题描述
我已经尝试过使用 raspberrypi 进行蓝牙通信的套接字编程。但是每次我因为错误而被拒绝连接时。我已经在 pi 上安装了所有必要的蓝牙包。
client code
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/rfcomm.h>
int main(int argc, char **argv)
{
struct sockaddr_rc addr = { 0 };
int s, status;
char dest[18] = "01:23:45:67:89:AB";
// allocate a socket
s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
// set the connection parameters (who to connect to)
addr.rc_family = AF_BLUETOOTH;
addr.rc_channel = (uint8_t) 1;
str2ba( dest, &addr.rc_bdaddr );
// connect to server
status = connect(s, (struct sockaddr *)&addr, sizeof(addr));
// send a message
if( status == 0 ) {
status = write(s, "hello!", 6);
}
if( status < 0 ) perror("uh oh");
close(s);
return 0;
}
服务器代码:
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/rfcomm.h>
int main(int argc, char **argv)
{
struct sockaddr_rc loc_addr = { 0 }, rem_addr = { 0 };
char buf[1024] = { 0 };
int s, client, bytes_read;
socklen_t 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;
bind(s, (struct sockaddr *)&loc_addr, sizeof(loc_addr));
// put socket into listening mode
listen(s, 1);
// accept one connection
client = accept(s, (struct sockaddr *)&rem_addr, &opt);
ba2str( &rem_addr.rc_bdaddr, buf );
fprintf(stderr, "accepted connection from %s\n", buf);
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;
}
当我的设备的可见性关闭时,它会说“主机已关闭” 当可见性打开并且我配对设备时,它说连接被拒绝。
解决方案
推荐阅读
- prometheus - 在 Prometheus 中,是否有一种方法可以仅使用一个查询来检测特定指标是否停止被主机分解?
- java - 在 Java Swing 中,当我使用 ActionListener 调用另一个类时,调用类 JFrame 是黑色的,没有图像,显示标签
- pandas - 选择 > 0 的系列元素
- kubernetes - 如何动态更新 Spring 云流实例索引?
- mongodb - 如何在 MongoDB 中进行分区?
- mysql - 通过基于 id 和 category 连接行来减少行数
- regex - 如何在没有正则表达式的情况下在 Google 表格中重新格式化此日期时间?
- react-native - React Native - 如何使用本机 Share.share 将 base64 字符串保存为 NAMED 文件
- reactjs - ReactJS - 从 2 个单独的 useState 设置变量
- javascript - 带有 vuejs 的 Firebase 数据库:default.collection 不是函数