C#开发蓝牙服务端,自动配对以及收发消息

来源:互联网 发布:忘记mac的开机密码 编辑:程序博客网 时间:2024/05/16 08:24

C#开发蓝牙服务端,自动配对以及收发消息

目前.Net平台最好用的蓝牙库是InTheHand.net,是由32feet.net提供的shared-source项目,提供短距离领域(personal area networking technologie)的通信功能,支持bluetooth,Infrared(IrDA)红外等.
//启动一个监听线程Thread listenThread = new Thread(ReceiveData);listenThread.IsBackground = true;listenThread.Start();//监听方法public void ReceiveData(){    while (1 == 1)     {        try        {           Guid mGUID = Guid.Parse("db764ac8-4b08-7f25-aafe-59d03c27bae3");               bluetoothListener = new BluetoothListener(mGUID);           bluetoothListener.Start();           bluetoothClient = bluetoothListener.AcceptBluetoothClient();           isConnected = true;            while (isConnected)            {               if (bluetoothClient != null && bluetoothClient.Connected)                {                    peerStream = bluetoothClient.GetStream();                }                else                {                    break;                }                byte[] buffer = new byte[100];                peerStream.Read(buffer, 0, 100);                receive = Encoding.UTF8.GetString(buffer).ToString();                if (receive == temp)                {                    isConnected = false;                }                Console.WriteLine(receive + "receiveMsg");            }            bluetoothListener.Stop();            bluetoothClient = null;        }        catch (Exception ex)        {            Console.Write(ex.Message);        }    } }

两个while循环是因为我的安卓app没法修改,没有做断开处理,所以强行在服务端断开了。
如果你蓝牙连接着的,并且和电脑配对上了,那用这个方法是可以接受消息的。

那么现在问题来了。

我的windows主机是没有输出设备的,木有显示器,而蓝牙配对有3中方法,其中justwork表示不验证,直接配对,但是客户端代码动不了,inTheHand.net也没有找到怎么设置配对模式。

最后找到蓝牙配对PING码确认的事件,直接把事件注册后,响应通过就行了。

EventHandler<BluetoothWin32AuthenticationEventArgs> handler = new EventHandler<BluetoothWin32AuthenticationEventArgs>(this.handleRequests);            BluetoothWin32Authentication authenticator = new BluetoothWin32Authentication(handler);public void handleRequests(Object thing, BluetoothWin32AuthenticationEventArgs args){    args.Confirm = true;}

基本上实现了Windows自动配对。

0 0
原创粉丝点击