当前位置: 首页 > >

C++ 用Winsock连接蓝牙

发布时间:

//连接蓝牙
BOOL CMyBlueT::ConnectBluetooth(int nNo)
{
?? ?//先关闭连接
?? ?closesocket(m_client_socket);
?? ?WSACleanup();


?? ?WSADATA wsd;
?? ?int err = WSAStartup(MAKEWORD(2, 2), &wsd);
?? ?if (err != 0)
?? ?{
?? ??? ?SetTips(L"WinSock初始化失败");
?? ??? ?return FALSE;
?? ?}
?? ?m_client_socket = socket(AF_BTH, SOCK_STREAM , BTHPROTO_RFCOMM);
?? ?if (m_client_socket == INVALID_SOCKET)
?? ?{
?? ??? ?SetTips(L"创建Socket失败");
?? ??? ?return FALSE;
?? ?}


?? ?SOCKADDR_BTH sa;
?? ?memset(&sa, 0, sizeof(sa));
?? ?sa.addressFamily = AF_BTH;
?? ?sa.btAddr = m_vBluetoothInfo[nNo].btAddr;
?? ?sa.port = 0;
?? ?sa.serviceClassId = RFCOMM_PROTOCOL_UUID;


?? ?//调用connect函数来连接到蓝牙套接字。
?? ?err = connect(m_client_socket, (SOCKADDR *)&sa, sizeof(sa));
?? ?if (err == INVALID_SOCKET)
?? ?{
?? ??? ?SetTips(L"连接蓝牙套接字失败。");
?? ??? ?//关闭Socket
?? ??? ?closesocket(m_client_socket);
?? ??? ?WSACleanup();
?? ??? ?return FALSE;
?? ?}
?? ?return TRUE;
}



友情链接: