天天看点

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

<a target="_blank" href="http://t.cn/RhfSa04">基于蓝牙对等网络通信就是使用Game Kit中的GKSession、GKSessionDelegate、GKPeerPickerController和GKPeerPickerControllerDelegate来实现。开发过程分为3个步骤:连接、发送数据和接收数据。</a>

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

<a target="_blank" href="http://t.cn/RhfSa04"></a>

<a target="_blank" href="http://t.cn/RhfSa04">1、连接</a>

<a target="_blank" href="http://t.cn/RhfSa04">由于对等网络连接过程有点复杂,贯穿了这些协议和类,我们绘制了连接过程的流程图。</a>

<a target="_blank" href="http://t.cn/RhfSa04">下面我们通过代码直接介绍连接流程,其中ViewController.h代码如下:</a>

<a target="_blank" href="http://t.cn/RhfSa04">[java] view plaincopy</a>

<a target="_blank" href="http://t.cn/RhfSa04">#import &lt;UIKit/UIKit.h&gt;  </a>

<a target="_blank" href="http://t.cn/RhfSa04">  </a>

<a target="_blank" href="http://t.cn/RhfSa04">#import &lt;GameKit/GameKit.h&gt;  </a>

<a target="_blank" href="http://t.cn/RhfSa04">   </a>

<a target="_blank" href="http://t.cn/RhfSa04">#define  GAMING 0          //游戏进行中  </a>

<a target="_blank" href="http://t.cn/RhfSa04">#define  GAMED  1          //游戏结束  </a>

<a target="_blank" href="http://t.cn/RhfSa04">@interface ViewController : UIViewController &lt;GKSessionDelegate, GKPeerPickerControllerDelegate&gt;  </a>

<a target="_blank" href="http://t.cn/RhfSa04">{  </a>

<a target="_blank" href="http://t.cn/RhfSa04">NSTimer *timer;  </a>

<a target="_blank" href="http://t.cn/RhfSa04">}  </a>

<a target="_blank" href="http://t.cn/RhfSa04">@property (weak, nonatomic) IBOutlet UILabel *lblTimer;  </a>

<a target="_blank" href="http://t.cn/RhfSa04">@property (weak, nonatomic) IBOutlet UILabel *lblPlayer2;  </a>

<a target="_blank" href="http://t.cn/RhfSa04">@property (weak, nonatomic) IBOutlet UILabel *lblPlayer1;  </a>

<a target="_blank" href="http://t.cn/RhfSa04">@property (weak, nonatomic) IBOutlet UIButton *btnConnect;  </a>

<a target="_blank" href="http://t.cn/RhfSa04">@property (weak, nonatomic) IBOutlet UIButton *btnClick;  </a>

<a target="_blank" href="http://t.cn/RhfSa04">@property (nonatomic, strong) GKPeerPickerController *picker;  </a>

<a target="_blank" href="http://t.cn/RhfSa04">@property (nonatomic, strong) GKSession *session;  </a>

<a target="_blank" href="http://t.cn/RhfSa04">- (IBAction)onClick:(id)sender;  </a>

<a target="_blank" href="http://t.cn/RhfSa04">- (IBAction)connect:(id)sender;  </a>

<a target="_blank" href="http://t.cn/RhfSa04">//清除UI画面上的数据  </a>

<a target="_blank" href="http://t.cn/RhfSa04">-(void) clearUI;  </a>

<a target="_blank" href="http://t.cn/RhfSa04">//更新计时器  </a>

<a target="_blank" href="http://t.cn/RhfSa04">-(void) updateTimer;  </a>

<a target="_blank" href="http://t.cn/RhfSa04">@end  </a>

<a target="_blank" href="http://t.cn/RhfSa04">使用Game Kit需要引入头文件&lt;GameKit/GameKit.h&gt;,之前需要把GameKit.framework框架添加到工程中。而且定义类的时候需要实现协议GKSessionDelegate和GKPeerPickerControllerDelegate,并且定义GKPeerPickerController类型的属性picker,定义GKSession类型的属性session。</a>

<a target="_blank" href="http://t.cn/RhfSa04">ViewController.m中创建GKPeerPickerController对象的代码如下:</a>

<a target="_blank" href="http://t.cn/RhfSa04">- (IBAction)connect:(id)sender {  </a>

<a target="_blank" href="http://t.cn/RhfSa04">_picker = [[GKPeerPickerController alloc] init];  </a>

<a target="_blank" href="http://t.cn/RhfSa04">_picker.delegate = self; ①  </a>

<a target="_blank" href="http://t.cn/RhfSa04">_picker.connectionTypesMask = GKPeerPickerConnectionTypeNearby;  ②  </a>

<a target="_blank" href="http://t.cn/RhfSa04">[_picker show];  </a>

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

<a target="_blank" href="http://t.cn/RhfSa04">_picker.connectionTypesMask = GKPeerPickerConnectionTypeNearby | GKPeerPickerConnectionTypeOnline;</a>

<a target="_blank" href="http://t.cn/RhfSa04">其中“在线”就是GKPeerPickerConnectionTypeOnline类型,“附近”就是GKPeerPickerConnectionTypeNearby类型。</a>

<a target="_blank" href="http://t.cn/RhfSa04">连接成功之后回调ViewController.m中的回调委托方法peerPickerController:didConnectPeer:toSession:代码:</a>

<a target="_blank" href="http://t.cn/RhfSa04">- (void)peerPickerController:(GKPeerPickerController *)pk didConnectPeer:(NSString *)peerID  </a>

<a target="_blank" href="http://t.cn/RhfSa04">toSession:(GKSession *) session  </a>

<a target="_blank" href="http://t.cn/RhfSa04">NSLog(@”建立连接”);  </a>

<a target="_blank" href="http://t.cn/RhfSa04">_session = session; ①  </a>

<a target="_blank" href="http://t.cn/RhfSa04">_session.delegate = self;  ②  </a>

<a target="_blank" href="http://t.cn/RhfSa04">[_session setDataReceiveHandler:self withContext:nil];  ③  </a>

<a target="_blank" href="http://t.cn/RhfSa04">_picker.delegate = nil;  </a>

<a target="_blank" href="http://t.cn/RhfSa04">[_picker dismiss]; ④  </a>

<a target="_blank" href="http://t.cn/RhfSa04">[_btnClick setEnabled:YES];  </a>

<a target="_blank" href="http://t.cn/RhfSa04">[_btnConnect setTitle:@"断开连接" forState:UIControlStateNormal];  </a>

<a target="_blank" href="http://t.cn/RhfSa04">//开始计时  </a>

<a target="_blank" href="http://t.cn/RhfSa04">timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self  </a>

<a target="_blank" href="http://t.cn/RhfSa04">selector:@selector(updateTimer)  </a>

<a target="_blank" href="http://t.cn/RhfSa04">userInfo:nil repeats:YES]; ⑤  </a>

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

<a target="_blank" href="http://t.cn/RhfSa04">- (GKSession *)peerPickerController:(GKPeerPickerController *)picker  </a>

<a target="_blank" href="http://t.cn/RhfSa04">sessionForConnectionType:(GKPeerPickerConnectionType)type {  </a>

<a target="_blank" href="http://t.cn/RhfSa04">GKSession *session = [[GKSession alloc] initWithSessionID: &lt;自定义SessionID&gt;  </a>

<a target="_blank" href="http://t.cn/RhfSa04">displayName:&lt;显示的名字&gt; sessionMode:GKSessionModePeer];  </a>

<a target="_blank" href="http://t.cn/RhfSa04">return session;  </a>

<a target="_blank" href="http://t.cn/RhfSa04">有的时候会话的状态会发生变化,我们要根据状态的变化做一些UI的清理和资源的释放。监测状态变化在委托方法session:peer:didChangeState:中实现,方法代码如下:</a>

<a target="_blank" href="http://t.cn/RhfSa04">- (void)session:(GKSession *)session peer:(NSString *)peerID  </a>

<a target="_blank" href="http://t.cn/RhfSa04">didChangeState:(GKPeerConnectionState)state  </a>

<a target="_blank" href="http://t.cn/RhfSa04">if (state == GKPeerStateConnected)  </a>

<a target="_blank" href="http://t.cn/RhfSa04">NSLog(@”connected”);  </a>

<a target="_blank" href="http://t.cn/RhfSa04">} else if (state == GKPeerStateDisconnected)  </a>

<a target="_blank" href="http://t.cn/RhfSa04">NSLog(@”disconnected”);  </a>

<a target="_blank" href="http://t.cn/RhfSa04">[self clearUI];  </a>

<a target="_blank" href="http://t.cn/RhfSa04">其中GKPeerStateConnected常量是已经连接状态,GKPeerStateDisconnected常量是断开连接状态。</a>

<a target="_blank" href="http://t.cn/RhfSa04">2、发送数据</a>

<a target="_blank" href="http://t.cn/RhfSa04">发送数据的代码如下:</a>

<a target="_blank" href="http://t.cn/RhfSa04">- (IBAction)onClick:(id)sender {  </a>

<a target="_blank" href="http://t.cn/RhfSa04">int count = [_lblPlayer1.text intValue];  </a>

<a target="_blank" href="http://t.cn/RhfSa04">_lblPlayer1.text = [NSString stringWithFormat:@"%i",++count];  </a>

<a target="_blank" href="http://t.cn/RhfSa04">NSString *sendStr = [NSString  </a>

<a target="_blank" href="http://t.cn/RhfSa04">stringWithFormat:@"{\"code\":%i,\"count\":%i}",GAMING,count]; ①  </a>

<a target="_blank" href="http://t.cn/RhfSa04">NSData* data = [sendStr dataUsingEncoding: NSUTF8StringEncoding];  </a>

<a target="_blank" href="http://t.cn/RhfSa04">if (_session) {  </a>

<a target="_blank" href="http://t.cn/RhfSa04">[_session sendDataToAllPeers:data  </a>

<a target="_blank" href="http://t.cn/RhfSa04">withDataMode:GKSendDataReliable  error:nil]; ②  </a>

<a target="_blank" href="http://t.cn/RhfSa04">3、接收数据</a>

<a target="_blank" href="http://t.cn/RhfSa04">为了接收数据首先需要在设置会话时候通过[_session setDataReceiveHandler:self withContext:nil]语句设置接收数据的处理程序是self。这样当数据到达时候就会触发下面的方法特定:</a>

<a target="_blank" href="http://t.cn/RhfSa04">- (void) receiveData:(NSData *)data  fromPeer:(NSString *)peer  </a>

<a target="_blank" href="http://t.cn/RhfSa04">inSession:(GKSession *)session  context:(void *)context  </a>

<a target="_blank" href="http://t.cn/RhfSa04">id jsonObj = [NSJSONSerialization JSONObjectWithData:data  </a>

<a target="_blank" href="http://t.cn/RhfSa04">options:NSJSONReadingMutableContainers error:nil];  </a>

<a target="_blank" href="http://t.cn/RhfSa04">NSNumber *codeObj = [jsonObj objectForKey:@"code"];  </a>

<a target="_blank" href="http://t.cn/RhfSa04">if ([codeObj intValue]== GAMING) {  </a>

<a target="_blank" href="http://t.cn/RhfSa04">NSNumber * countObj= [jsonObj objectForKey:@"count"];  </a>

<a target="_blank" href="http://t.cn/RhfSa04">_lblPlayer2.text = [NSString stringWithFormat:@"%@",countObj];  </a>

<a target="_blank" href="http://t.cn/RhfSa04">} else if ([codeObj intValue]== GAMED) {  </a>

<a target="_blank" href="http://t.cn/RhfSa04">上面的代码是接收到数据之后,进行JSON解码,取出游戏状态和点击次数。</a>

<a target="_blank" href="http://t.cn/RhfSa04">主要的程序代码就是这些,根据具体的业务情况还可以能有所变化,读者可以下载完整代码在两台之间设备或是一个设备一个模拟器之间进行测试。</a>