winsock:蓝牙客户端-服务器未连接
Posted
技术标签:
【中文标题】winsock:蓝牙客户端-服务器未连接【英文标题】:winsock : bluetooth client-server not connecting 【发布时间】:2015-09-11 03:28:43 【问题描述】:我已经使用winsock编写了一个小型蓝牙服务器和客户端程序
我无法弄清楚为什么客户端没有连接到服务器。两者都在不同的电脑上运行,并且 两者都是通过蓝牙配对的。
服务器代码是
void server()
SOCKET server_socket = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM), new_socket;
if (server_socket == INVALID_SOCKET)
cout << "socket creation failed...Error code : " << WSAGetLastError() << endl;
Sleep(2000);
return;
cout << "socket created" << endl;
SOCKADDR_BTH sa, sa2;
int channel = 0, len=sizeof(sa2);
memset(&sa, 0, sizeof(SOCKADDR_BTH));
sa.addressFamily = AF_BTH;
sa.port = channel & 0xff;
//bind
if (bind(server_socket, (SOCKADDR *)&sa, sizeof(sa)))
cout << "Binding failed...Error code : " << WSAGetLastError() << endl;
closesocket(server_socket);
Sleep(2000);
return;
cout << "binding done" << endl;
cout << "\nWaiting for client" << endl;
listen(server_socket, 3);
new_socket = accept(server_socket, (sockaddr *)&sa2, &len);
cout<<"connection accepted";
客户端代码是
void client()
SOCKET client_socket = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);
int channel = 0;
BTH_ADDR bt_addr;
char* server_address = "34:02:86:26:c1:62";
if (client_socket == INVALID_SOCKET)
cout << "socket creation failed...Error code : " << WSAGetLastError() << endl;
Sleep(2000);
return;
cout << "socket created" << endl;
if (str2ba(server_address, &bt_addr) == 1)
cout << "address conversion error..." << endl;
Sleep(2000);
return;
SOCKADDR_BTH sa;
sa.addressFamily = AF_BTH;
sa.port = channel & 0xff;
sa.btAddr = bt_addr;
cout << "\nconnecting..." << endl;
if (connect(client_socket, (sockaddr *)&sa, sizeof(sockaddr)))
cout << "Error in connecting...Error code : " << WSAGetLastError() << endl;
closesocket(client_socket);
Sleep(2000);
return;
cout << "\nConnected" << endl;
Sleep(2000);
int str2ba(char *str_bt_addr, BTH_ADDR *bt_addr)//for converting string to bluetooth address
unsigned int addr[6];
if (sscanf_s(str_bt_addr, "%02x:%02x:%02x:%02x:%02x:%02x",
&addr[0], &addr[1], &addr[2], &addr[3], &addr[4], &addr[5]) != 6)
return 1;
*bt_addr = 0;
BTH_ADDR tmpaddr;
int i;
for (i = 0;i < 6;++i)
tmpaddr = (BTH_ADDR)(addr[i] & 0xff);
*bt_addr = ((*bt_addr) << 8) + tmpaddr;
return 0;
为什么这些没有连接?我错过了什么? 请帮我。 提前感谢您的帮助。
【问题讨论】:
【参考方案1】:在我短暂的蓝牙体验中,问题通常出在 SOCKADDR_BTH 声明中。
我硬编码了每个端点的 MAC 地址:“38:2D:E8:B9:FA:EB” 十六进制
RemoteEndPoint.btAddr = BTH_ADDR(0x382DE8B9FAEB);
还要确保你的端口在每个端点上都是相同的,我使用了:
RemoteEndPoint.port = 0;
和
LocalEndpoint.port = 0;
我在这里有一些代码:C++ WinSock Bluetooth Connection - AT Command - Error Received 我也有问题。
蓝牙并不像某些人想象的那么容易,因此 OP 没有收到任何答案
【讨论】:
以上是关于winsock:蓝牙客户端-服务器未连接的主要内容,如果未能解决你的问题,请参考以下文章
Winsock - 客户端断开连接,关闭套接字循环/最大连接数