蓝牙设备与PC socket通讯

1. 蓝牙适配器插入PC USB口(前提蓝牙适配器驱动要装好)
2. 开启蓝牙key或蓝牙手机等蓝牙设备。

3. 运行一下程序

#include "stdafx.h"

#include 
#include 
#include 

#pragma comment(lib,"ws2_32.lib")
#pragma comment(lib,"irprops.lib")

int SDPGetPort( const char *addr , LPGUID guid )
{
	int nRet = 0;
	int port = 0;
	HANDLE h ;
	WSAQUERYSET *qs ;
	DWORD flags = 0;
	DWORD qs_len ;
	bool done ;
	qs_len = sizeof(WSAQUERYSET ) ;
	qs = (WSAQUERYSET* ) malloc( qs_len ) ;
	ZeroMemory( qs , qs_len ) ;
	qs->dwSize = sizeof(WSAQUERYSET ) ;
	qs->lpServiceClassId = guid ;
	qs->dwNameSpace = NS_BTH ;
	qs->dwNumberOfCsAddrs = 0;
	qs->lpszContext = (LPSTR) addr ;
	flags = LUP_FLUSHCACHE | LUP_RETURN_ADDR;
	nRet = WSALookupServiceBegin ( qs , flags, &h );
	if( SOCKET_ERROR == nRet ) {
		nRet = WSAGetLastError();
		ExitProcess ( 2 ) ;
	}
	done = false ;
	while ( ! done ) {
		if( SOCKET_ERROR == WSALookupServiceNext (h , flags, &qs_len , qs) ) {
			int error = WSAGetLastError ( ) ;
			if( error == WSAEFAULT ) {
				free(qs ) ;
				qs = (WSAQUERYSET* ) malloc( qs_len ) ;
			} else if (error == WSA_E_NO_MORE ) {
				done = true ;
			} else {
				ExitProcess ( 2 ) ;
			}
		} else {
			SOCKADDR_BTH *sa =
				(SOCKADDR_BTH* )qs->lpcsaBuffer->RemoteAddr.lpSockaddr ;
			port = sa->port ;
		}
	}
	free(qs ) ;
	WSALookupServiceEnd( h ) ;
	return port ;
}
int _tmain(int argc , _TCHAR* argv[ ] )
{
	int nRet = 0;
	SOCKET sock ;
	SOCKADDR_BTH sa = { 0 } ;
	int sa_len = sizeof(sa ) ;
	
	WORD wVersionRequested ;
	WSADATA wsaData ;
	wVersionRequested = MAKEWORD( 2, 0 );
	if( WSAStartup( wVersionRequested, &wsaData ) != 0 ) {
		ExitProcess ( 2 ) ;
	}

	if( SOCKET_ERROR == WSAStringToAddress ( _T("00:15:83:5c:60:fe")/*argv[1]*/ , AF_BTH ,
		NULL, (LPSOCKADDR) &sa, &sa_len ) ) {
			nRet = GetLastError();
			ExitProcess ( 2 ) ;
	}
	// query it for the right port
	// create the socket
	sock = socket (AF_BTH , SOCK_STREAM , BTHPROTO_RFCOMM ) ;
	if( SOCKET_ERROR == sock ) {
		ExitProcess ( 2 ) ;
	}
	// fill in the rest of the SOCKADDR_BTH struct
	sa.port = SDPGetPort ("00:15:83:5c:60:fe", (LPGUID)&SerialPortServiceClass_UUID/*(LPGUID) &SAMPLE_UUID*/ ) ;
	if( sa.port == 0 ) {
		ExitProcess ( 2 ) ;
	}
	
	nRet = connect( sock, (LPSOCKADDR) &sa , sa_len );
	if( SOCKET_ERROR == nRet ) {
		nRet = GetLastError();
		ExitProcess ( 2 ) ;
	}
	send ( sock , "hello!" , 5, 0 );
	closesocket (sock ) ;
	return 0;
}
4. 注: 
00:15:83:5c:60:fe 为 蓝牙设备的mac地址为六段。

connet运行时,出现连接设备的窗口,需要点击下一步,这里把mac地址固定,相当于省略了选的哪一步。

《Cambridge - Bluetooth Essentials for Programmers.pdf》 网上可以下载,可以参考。





你可能感兴趣的:(windows/VC,蓝牙相关)