应该采用RFCOMM虚拟串口方式来进行通信,原理跟socket通信类似,不同的是使用的通信协议不同,本人结合相关的API,做了以下最简单的封装。
1、获取本地蓝牙设备与附近蓝牙设备信息
2、通信类
/*
通信类:只是对于客户端通信
Initialize
Create
Connect
Send
Receive
Close
Finalize
*/
class BlueToothSimple
{
public:
bool Initialize();
bool Create();
bool Connect(const char* straddr, const char* guid = "0000fd2d-0000-1000-8000-00805f9b34fb");
bool Send(const char* msgToServer);
// 返回字符串
string Receive();
// 返回特殊的数据,针对于\r\n 划分开的字符串
vector<CString> ReceiveEx();
bool Close();
void Finalize();
protected:
int error;
SOCKET btSocket;
};
3、支持服务器客户端蓝牙虚拟通信接口
class BlueToothSocket
{
public:
BlueToothSocket();
~BlueToothSocket();
BOOL StartSearchBthDev(IN DWORD dwControlFlags);
BOOL GetNextBthDev(
IN OUT BTHDEV_INFO *pcBthDevInfo,
IN DWORD dwControlFlags = LUP_RETURN_NAME | LUP_RETURN_ADDR | LUP_FLUSHCACHE
);
BOOL EndSearchBthDev();
bool Initialize();
void Finalize();
BOOL Create(int af = AF_BTH, int type = SOCK_STREAM, int protocol = BTHPROTO_RFCOMM);
BOOL Close();
int Bind(BTH_ADDR sktAddr = 0, ULONG port = BT_PORT_ANY);
int Listen(IN int backlog);
int GetSockName(BTH_ADDR *psktAddr, ULONG *port);
int SetBthService(TCHAR *lpServiceName);
int Accept(BlueToothSocket *pcBth);
int GetBTHAddr(const char* straddr, BTH_ADDR* btaddr);
int Connect(BTH_ADDR sktAddr, ULONG port, int nMSecond = -1);
int Send(LPVOID lpData, int len, int flags = 0);
int Recv(LPVOID lpData, int len, int flags = 0);
int SendAll(LPVOID lpData, int len, int flags = 0);
int RecvAll(LPVOID lpData, int len, int flags = 0);
private:
void HexMac2String(BTH_ADDR dw64Addr, TCHAR *pstrMac);
};
资源下载地址:https://download.csdn.net/download/u011269801/89296309?spm=1001.2014.3001.5503