技术开发 频道

.NET Compact Framework下的Bluetooth广播程序的开发

 监听线程

 private void ListenLoop()

 {

 byte[] buffer = new byte[4];

 string dataToSend = "Thanks for subscription";

 byte[] dataBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(dataToSend);

 while (listening)

 {

 try

 {

 BluetoothClient client = listener.AcceptBluetoothClient();

 WriteMessage("Get a subscription from " + client.RemoteMachineName);

 clientList.Add(client);

 System.IO.Stream ns = client.GetStream();

 ns.Write(dataBuffer, 0, dataBuffer.Length);

 }

 catch

 {

 break;

 }

 }

 listener.Stop();

 }

 监听线程负责处理监听订阅请求,并把订阅的设备增加到订阅列表中。AcceptBluetoothClient()会挂起改线程,直到有新的设备进行订阅。

 广播线程

  private void BroadcastLoop()

 {

 List<BluetoothClient> tempClientList = new List<BluetoothClient>();

 while (listening)

 {

 System.Threading.Thread.Sleep(5000);

 string dataToSend = "Broadcast Message at " + System.DateTime.Now.ToLongTimeString();

 byte[] dataBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(dataToSend);

 tempClientList.Clear();

 foreach (BluetoothClient client in clientList)

 {

 try

 {

 System.IO.Stream ns = client.GetStream();

 ns.Write(dataBuffer, 0, dataBuffer.Length);

 WriteMessage("Sent message to " + client.RemoteMachineName);

 }

 catch

 {

 //connection is broken.

 tempClientList.Add(client);

 continue;

 }

 }

 //clean up the broken connections.

 foreach (BluetoothClient client in tempClientList)

 {

 clientList.Remove(client);

 }

 }

 }

 广播线程负责对已经订阅的设备进行消息广播,同时管理已经断开的链接。在实际应用中,这个线程需要根据需求来更改业务流程。

0
相关文章