socket进行RFCOMM连接(Wince 6.0)

亲自测试一下代码使用socket进行配对连接,连接成功后可以使用recv和send等接口进行接收发送数据


SOCKADDR_BTH sa;
	WSADATA wsaData;
	int channel = 1;
	if ( 0 != WSAStartup(MAKEWORD(2,2), &wsaData) )
	{
		MessageBox(NULL,L"Failed to retrive socket version.",0,0);
		return -1;
	}
	SOCKET m_socketClient = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);
	if ( m_socketClient==INVALID_SOCKET )
	{
		CString str = _T("");
		str.Format(L"error of creatsocket is %d",GetLastError());
		MessageBox(NULL,str,0,0); 
		return -1;
	}
	//密码配对
	char* szPIN = "1234";
	BTH_SOCKOPT_SECURITY bth_sockopt;

	memset(&bth_sockopt, 0, sizeof(bth_sockopt));
	bth_sockopt.iLength = strlen(szPIN);
	bth_sockopt.btAddr = ServerAddress;
	char szBuf[32] ;  
	memset(szBuf, 0, sizeof(szBuf));
	strcpy(szBuf, szPIN);
	memcpy(bth_sockopt.caData,szBuf,strlen(szBuf)+1);  

	if(setsockopt(m_socketClient, SOL_RFCOMM, SO_BTH_SET_PIN, (char *)&bth_sockopt, sizeof(BTH_SOCKOPT_SECURITY)) == SOCKET_ERROR )
	{
		int nError = WSAGetLastError();
		MessageBox(NULL,L"配对失败",0,0);
		WSACleanup();
	}//配对结束


	//连接
	memset (&sa, 0, sizeof(sa));
	sa.btAddr = ServerAddress; //b is a BT_ADDR variable
	sa.addressFamily = AF_BT;
	sa.port = channel & 0xff;
	//sa.serviceClassId = guid;
	if (connect (m_socketClient, (SOCKADDR *)&sa, sizeof(sa))) 
	{
		closesocket (m_socketClient);
		MessageBox(NULL,L"connect Socket error",0,0);
		return -1;
	}


你可能感兴趣的:(Wince,socket通信)