我正在尝试使用蓝牙连接2台笔记本电脑。 这是我用来制作服务器的代码:
WSADATA wsd;
WSAStartup (MAKEWORD(1,0), &wsd);
SOCKET server_socket = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);
SOCKADDR_BTH sa;
memset(&sa, 0, sizeof(sa));
sa.addressFamily = AF_BTH;
sa.port = 0 & 0xFF;
if(0 != bind(server_socket, (SOCKADDR *)&sa, sizeof(sa)))
{
std::cout << "BIND ERROR: " << WSAGetLastError () << std::endl;
closesocket(server_socket);
return false;
}
if(0 != listen (server_socket, 5))
{
std::cout << "LISTEN ERROR: " << WSAGetLastError () << std::endl;
closesocket(server_socket);
return false;
}
SOCKADDR_BTH sa2;
int size = sizeof(sa2);
SOCKET s2 = accept(server_socket, (SOCKADDR*)&sa2, &size);
if(s2 == INVALID_SOCKET)
{
std::cout << "ACCEPT ERROR: " << WSAGetLastError () << std::endl;
return false;
}
else
{
std::cout << "Connected? " << WSAGetLastError () << std::endl;
}
以及以下作为客户:
WSADATA wsd;
WSAStartup (MAKEWORD(1,0), &wsd);
SOCKET client_socket = socket (AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);
SOCKADDR_BTH sa;
memset (&sa, 0, sizeof(sa));
sa.addressFamily = AF_BTH;
sa.btAddr = (BTH_ADDR)d.getDeviceAddress();
sa.port = 0;
sa.serviceClassId = *d.getLpServiceClassId();
if(client_socket == INVALID_SOCKET)
{
std::cout << "SOCKET ERROR: " << WSAGetLastError () << std::endl;
return false;
}
if (0 != connect (client_socket, (SOCKADDR *)&sa, sizeof(sa)))
{
std::cout << "CONNECT ERROR: " << WSAGetLastError () << std::endl;
return false;
}
else
{
//std::cout << "CONNECT ERROR: " << WSAGetLastError () << std::endl;
//Perform error handling.s
send(client_socket, "ABC",3,0);
closesocket (client_socket);
return true;
}
其中“b”是我给出的蓝牙设备作为参数,bluetoothdevice类有以下字段:
LPSOCKADDR local_address;
LPSOCKADDR device_address;
LPGUID lp_service_class_id;
这应该工作。但是当我尝试连接到服务器时,服务器什么也得不到,客户端给我10060错误。
此错误表示:
WSAETIMEDOUT 10060
The I/O timed out at the Bluetooth radio level (PAGE_TIMEOUT).
是否有人在Windows上使用蓝牙堆栈并知道此错误来自哪里?
答案 0 :(得分:0)
您是否使用蓝牙SDP注册了服务?如果不是,我想,您将无法使用客户端代码中的当前方法进行连接。来自MSDN:
The bind function does not automatically advertise the server application using the Bluetooth SDP; applications must call the WSASetService function to be found by remote Bluetooth applications.
另请参阅bind
和connect
funcs的蓝牙文档:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa362901%28v=vs.85%29.aspx http://msdn.microsoft.com/en-us/library/windows/desktop/aa362901%28v=vs.85%29.aspx
据我了解,另一种方法是您可以尝试在服务器端和客户端明确指定port
。但它仅适用于游乐场应用程序。
有关蓝牙使用的更多信息,请参阅http://msdn.microsoft.com/en-us/library/windows/desktop/aa363058%28v=vs.85%29.aspx。