iOS网络编程实践--蓝牙对等网络通信实例讲解

来源:互联网 发布:淘宝飞机头模特 编辑:程序博客网 时间:2024/04/28 03:03

基于蓝牙对等网络通信就是使用Game Kit中的GKSession、GKSessionDelegate、GKPeerPickerController和GKPeerPickerControllerDelegate来实现。开发过程分为3个步骤:连接、发送数据和接收数据。

下面我们通过一个实例介绍一下基于蓝牙对等网络通信过程。用户点击“连接”按钮,建立连接过程中会出现连接对话框,根据具体情况也会弹出其它的对话框。这些都是针对蓝牙对等网络标准对话框,而Wifi对等网络没有标准对话框可以使用,需要开发者自己实现。当两个设备连接好之后,两个玩家就可以连续轻点“点击”按钮,点击的次数会传递给对方,倒计时时间是30秒。

4

1、连接

由于对等网络连接过程有点复杂,贯穿了这些协议和类,我们绘制了连接过程的流程图。

5

下面我们通过代码直接介绍连接流程,其中ViewController.h代码如下:

[java] view plaincopy
  1. #import <UIKit/UIKit.h>  
  2.   
  3. #import <GameKit/GameKit.h>  
  4.   
  5.    
  6.   
  7. #define  GAMING 0          //游戏进行中  
  8.   
  9. #define  GAMED  1          //游戏结束  
  10.   
  11.    
  12.   
  13. @interface ViewController : UIViewController <GKSessionDelegate, GKPeerPickerControllerDelegate>  
  14.   
  15. {  
  16.   
  17. NSTimer *timer;  
  18.   
  19. }  
  20.   
  21. @property (weak, nonatomic) IBOutlet UILabel *lblTimer;  
  22.   
  23.    
  24.   
  25. @property (weak, nonatomic) IBOutlet UILabel *lblPlayer2;  
  26.   
  27. @property (weak, nonatomic) IBOutlet UILabel *lblPlayer1;  
  28.   
  29. @property (weak, nonatomic) IBOutlet UIButton *btnConnect;  
  30.   
  31. @property (weak, nonatomic) IBOutlet UIButton *btnClick;  
  32.   
  33.    
  34.   
  35. @property (nonatomic, strong) GKPeerPickerController *picker;  
  36.   
  37. @property (nonatomic, strong) GKSession *session;  
  38.   
  39.    
  40.   
  41. - (IBAction)onClick:(id)sender;  
  42.   
  43. - (IBAction)connect:(id)sender;  
  44.   
  45.    
  46.   
  47. //清除UI画面上的数据  
  48.   
  49. -(void) clearUI;  
  50.   
  51.    
  52.   
  53. //更新计时器  
  54.   
  55. -(void) updateTimer;  
  56.   
  57.    
  58.   
  59. @end  


使用Game Kit需要引入头文件<GameKit/GameKit.h>,之前需要把GameKit.framework框架添加到工程中。而且定义类的时候需要实现协议GKSessionDelegate和GKPeerPickerControllerDelegate,并且定义GKPeerPickerController类型的属性picker,定义GKSession类型的属性session。

ViewController.m中创建GKPeerPickerController对象的代码如下:

[java] view plaincopy
  1. - (IBAction)connect:(id)sender {  
  2.   
  3. _picker = [[GKPeerPickerController alloc] init];  
  4.   
  5. _picker.delegate = self; ①  
  6.   
  7. _picker.connectionTypesMask = GKPeerPickerConnectionTypeNearby;  ②  
  8.   
  9. [_picker show];  
  10.   
  11. }  


用户点击的连接按钮时,触发connect:方法。在该方法中创建GKPeerPickerController对象。创建完成不要忘记设置GKPeerPickerController委托为self,第②行代码所示。在第③行代码中connectionTypesMask属性是设置对等网络连接类型,其中有两种类型选择:GKPeerPickerConnectionTypeNearby和GKPeerPickerConnectionTypeOnline,GKPeerPickerConnectionTypeNearby用于蓝牙通讯也是默认的通讯方法,GKPeerPickerConnectionTypeOnline用于Wifi通讯的局域网通讯,这种方式麻烦,需要开发人员自己设计UI画面,自己使用Bonjour服务发现管理连接,以及自己编写输入输出流实现通讯。如果给用户一个选择对话框,代码可以如下编写:

_picker.connectionTypesMask = GKPeerPickerConnectionTypeNearby | GKPeerPickerConnectionTypeOnline;

6

其中“在线”就是GKPeerPickerConnectionTypeOnline类型,“附近”就是GKPeerPickerConnectionTypeNearby类型。

连接成功之后回调ViewController.m中的回调委托方法peerPickerController:didConnectPeer:toSession:代码:

[java] view plaincopy
  1. - (void)peerPickerController:(GKPeerPickerController *)pk didConnectPeer:(NSString *)peerID  
  2.   
  3. toSession:(GKSession *) session  
  4.   
  5. {  
  6.   
  7. NSLog(@”建立连接”);  
  8.   
  9. _session = session; ①  
  10.   
  11. _session.delegate = self;  ②  
  12.   
  13. [_session setDataReceiveHandler:self withContext:nil];  ③  
  14.   
  15. _picker.delegate = nil;  
  16.   
  17. [_picker dismiss]; ④  
  18.   
  19. [_btnClick setEnabled:YES];  
  20.   
  21. [_btnConnect setTitle:@"断开连接" forState:UIControlStateNormal];  
  22.   
  23. //开始计时  
  24.   
  25. timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self  
  26.   
  27. selector:@selector(updateTimer)  
  28.   
  29. userInfo:nil repeats:YES]; ⑤  
  30.   
  31. }  


上述代码第①行_session = session将委托方法中返回的会话参数赋值给成员变量,这样我们就获得了一个会话对象。这种方式中,会话ID是应用程序的包ID,如果想自己分配会话ID,可以实现下面委托方法,在方法中使用GKSession的构造方法initWithSessionID:displayName: sessionMode:,自己创建会话对象。

[java] view plaincopy
  1. - (GKSession *)peerPickerController:(GKPeerPickerController *)picker  
  2.   
  3. sessionForConnectionType:(GKPeerPickerConnectionType)type {  
  4.   
  5. GKSession *session = [[GKSession alloc] initWithSessionID: <自定义SessionID>  
  6.   
  7. displayName:<显示的名字> sessionMode:GKSessionModePeer];  
  8.   
  9. return session;  
  10.   
  11. }  


有的时候会话的状态会发生变化,我们要根据状态的变化做一些UI的清理和资源的释放。监测状态变化在委托方法session:peer:didChangeState:中实现,方法代码如下:

[java] view plaincopy
  1. - (void)session:(GKSession *)session peer:(NSString *)peerID  
  2.   
  3. didChangeState:(GKPeerConnectionState)state  
  4.   
  5. {  
  6.   
  7. if (state == GKPeerStateConnected)  
  8.   
  9. {  
  10.   
  11. NSLog(@”connected”);  
  12.   
  13. [_btnConnect setTitle:@"断开连接" forState:UIControlStateNormal];  
  14.   
  15. [_btnClick setEnabled:YES];  
  16.   
  17. else if (state == GKPeerStateDisconnected)  
  18.   
  19. {  
  20.   
  21. NSLog(@”disconnected”);  
  22.   
  23. [self clearUI];  
  24.   
  25. }  
  26.   
  27. }  


其中GKPeerStateConnected常量是已经连接状态,GKPeerStateDisconnected常量是断开连接状态。

2、发送数据

发送数据的代码如下:

[java] view plaincopy
  1. - (IBAction)onClick:(id)sender {  
  2.   
  3. int count = [_lblPlayer1.text intValue];  
  4.   
  5. _lblPlayer1.text = [NSString stringWithFormat:@"%i",++count];  
  6.   
  7. NSString *sendStr = [NSString  
  8.   
  9. stringWithFormat:@"{\"code\":%i,\"count\":%i}",GAMING,count]; ①  
  10.   
  11. NSData* data = [sendStr dataUsingEncoding: NSUTF8StringEncoding];  
  12.   
  13. if (_session) {  
  14.   
  15. [_session sendDataToAllPeers:data  
  16.   
  17. withDataMode:GKSendDataReliable  error:nil]; ②  
  18.   
  19. }  
  20.   
  21. }  


3、接收数据

为了接收数据首先需要在设置会话时候通过[_session setDataReceiveHandler:self withContext:nil]语句设置接收数据的处理程序是self。这样当数据到达时候就会触发下面的方法特定:

[java] view plaincopy
  1. - (void) receiveData:(NSData *)data  fromPeer:(NSString *)peer  
  2.   
  3. inSession:(GKSession *)session  context:(void *)context  
  4.   
  5. {  
  6.   
  7. id jsonObj = [NSJSONSerialization JSONObjectWithData:data  
  8.   
  9. options:NSJSONReadingMutableContainers error:nil];  
  10.   
  11. NSNumber *codeObj = [jsonObj objectForKey:@"code"];  
  12.   
  13. if ([codeObj intValue]== GAMING) {  
  14.   
  15. NSNumber * countObj= [jsonObj objectForKey:@"count"];  
  16.   
  17. _lblPlayer2.text = [NSString stringWithFormat:@"%@",countObj];  
  18.   
  19. else if ([codeObj intValue]== GAMED) {  
  20.   
  21. [self clearUI];  
  22.   
  23. }  
  24.   
  25. }  


上面的代码是接收到数据之后,进行JSON解码,取出游戏状态和点击次数。

主要的程序代码就是这些,根据具体的业务情况还可以能有所变化,读者可以下载完整代码在两台之间设备或是一个设备一个模拟器之间进行测试。

原创粉丝点击