[ios2]蓝牙通信【转】
iPhone开发应用中关于GameKit蓝牙实例讲解是本文要介绍的内容,主要是来了解并学习GameKit蓝牙实例。介绍一下这个实例实现的是两个带有蓝牙设备的touch之间的一个小游戏,在界面上有个可以响应事件的UIView(之前说过)可以点击,然后看谁新达到WINNING_TAP_COUNT (游戏中一常量可以自己设置)谁先达到谁就赢了,然后通知对方。还要引入GameKit.framework框架
头文件BlueToothViewController.h:
[pre]
- //
- // // BlueToothViewController.h
- // BlueTooth //
- // Created by mingchun liu on 09-11-24. // Copyright sdie 2009. All rights reserved.
- //
- #import <UIKit/UIKit.h> #import
<GameKit/GameKit.h> - #define START_GAME_KEY @"startgame"
- #define END_GAME_KEY @"endgame" #define TAP_COUNT_KEY @"taps"
- #define WINNING_TAP_COUNT 50
- #define AMIPHD_P2P_SESSION_ID @"amiphdp2p2"//这个是蓝牙协议
- @interface BlueToothViewController : UIViewController<GKPeerPickerControllerDelegate,GKSessionDelegate>{ BOOL actingAsHost;//是否提供服务,客户端还是服务器端
- int playerTapCount;//记录玩家点击次数 int opponentTapCount;//对方点击次数
- IBOutlet UILabel *playerTapCountLabel;//显示玩家点击次数 IBOutlet UILabel *opponentTapCountLabel;//显示对手点击次数
- NSString *opponentID;//对方标识符 GKSession *gkSession;
- IBOutlet UILabel *startQuitButton;//开始退出按钮
- }
- @property BOOL actingAsHost; @property int playerTapCount;
- @property int opponentTapCount; @property (nonatomic,retain) GKSession *gkSession;
- @property (nonatomic,retain) NSString *opponentID;
- @property (nonatomic,retain)UILabel *playerTapCountLabel;
- @property (nonatomic,retain)UILabel *opponentTapCountLabel;
- @property (nonatomic,retain)UILabel *startQuitButton;
- -(IBAction) handleStartQuitTapped;//处理开始退出操作 -(IBAction) handleTapViewTapped;//处理点击UIView的操作
- -(void) updateTapCountLabels;//更新显示 -(void) initGame;//初始化游戏
- -(void) hostGame; -(void) joinGame;//加入游戏
- -(void) endGame;//结束游戏 -(void) showEndGameAlert;//弹出结束游戏对话框
- @end
- #import "BlueToothViewController.h"
- @implementation BlueToothViewController
- @synthesize actingAsHost; @synthesize playerTapCount;
- @synthesize opponentID; @synthesize playerTapCountLabel;
- @synthesize opponentTapCountLabel;
- @synthesize startQuitButton; @synthesize gkSession;
- @synthesize opponentTapCount;
- -(IBAction) handleStartQuitTapped {//建立链接操作,弹出链接窗口显示在线 if (! opponentID) {//如果对手ID为空就建立服务端提供服务
- actingAsHost =
YES; GKPeerPickerController *peerPickerController =[[GKPeerPickerController alloc] init]; - peerPickerController.delegate =
self; peerPickerController.connectionTypesMask = - GKPeerPickerConnectionTypeNearby; [peerPickerController show];
- } }
- -(IBAction) handleTapViewTapped {//点击操作 playerTapCount++;
- [self updateTapCountLabels]; // did we just win?
- BOOL playerWins =
playerTapCount >= WINNING_TAP_COUNT;//当点击达到一定次数时 // send tap count to peer - NSMutableData *message = [[NSMutableData alloc] init];//传的数据类型为nsdata类型的 NSKeyedArchiver *archiver =
- [[NSKeyedArchiver
alloc] initForWritingWithMutableData:message]; [archiver
encodeInt:playerTapCount forKey: TAP_COUNT_KEY]; - if (playerWins) [archiver encodeBool:YES forKey:END_GAME_KEY];
- [archiver finishEncoding];//打包传数据 GKSendDataMode
sendMode = - playerWins
? GKSendDataReliable :
GKSendDataUnreliable;//判断用可靠的链接还是不可靠的链接 [gkSession
sendDataToAllPeers: message withDataMode:sendMode error:NULL];//发送数据 - [archiver release]; [message release];
- // also end game locally if (playerWins)
- [self endGame]; }
- -(void) updateTapCountLabels {
- playerTapCountLabel.text = [NSString stringWithFormat:@"%d", playerTapCount];
- opponentTapCountLabel.text = [NSString stringWithFormat:@"%d", opponentTapCount];
- } -(void) initGame {
- ; ;
- } -(void) hostGame {
- [self initGame]; NSMutableData *message = [[NSMutableData alloc] init];
- NSKeyedArchiver *archiver
= [[NSKeyedArchiver
alloc]
initForWritingWithMutableData:message]; - [archiver encodeBool:YES forKey:START_GAME_KEY]; [archiver finishEncoding];
- NSError *sendErr =
nil; [gkSession sendDataToAllPeers: message - withDataMode:GKSendDataReliable error:&sendErr]; if (sendErr)
- NSLog (@"send greeting failed: %@", sendErr); // change state of startQuitButton
- startQuitButton.text = @"Quit"; [message release];
- [archiver release]; [self updateTapCountLabels];
- } -(void) joinGame {
- [self initGame]; startQuitButton.text = @"Quit";
- [self updateTapCountLabels]; }
- //一下是代理方法
- -(GKSession *) peerPickerController: (GKPeerPickerController*) controller
- sessionForConnectionType: (GKPeerPickerConnectionType) type { if (!gkSession) {//如果没有链接时建立连接
- gkSession = [[GKSession alloc] initWithSessionID:AMIPHD_P2P_SESSION_ID//根据此值判断用的是什么链接
- displayName:nil//在线用户名
sessionMode:GKSessionModePeer]; - gkSession.delegate =
self; } - return gkSession; }
- - (void)peerPickerController:(GKPeerPickerController *)picker didConnectPeer:(NSString *)peerID toSession:(GKSession *)session
- {//当picker接收到数据后将其释放掉,否则进入不了界面 [picker dismiss];
- picker.delegate =
nil; [picker autorelease]; - } - (void)session:(GKSession *)session
- didReceiveConnectionRequestFromPeer:(NSString *)peerID {//已接受连接请求的代理方法 actingAsHost =
NO;//设为客户端 - }
- - (void)session:(GKSession *)session peer:(NSString *)peerID didChangeState:(GKPeerConnectionState)state {//状态改变时触发的代理方法
- switch (state) {
- case GKPeerStateConnected: [session setDataReceiveHandler: self withContext: nil];
- opponentID = peerID;//改变opponentID的值 actingAsHost ? [self hostGame] : [self joinGame];//
- break; }
- }
- -
(void) receiveData: (NSData*) data fromPeer: (NSString*)
peerID inSession: (GKSession*) session context:
(void*) context {//接受数据时的代理操作 - NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
- if ([unarchiver containsValueForKey:TAP_COUNT_KEY]) { opponentTapCount = [unarchiver decodeIntForKey:TAP_COUNT_KEY];
- [self updateTapCountLabels]; }
- if ([unarchiver containsValueForKey:END_GAME_KEY]) { [self endGame];
- } if ([unarchiver containsValueForKey:START_GAME_KEY]) {
- [self joinGame]; }
- [unarchiver release]; }
- //以上是代理方法
- -(void) showEndGameAlert { BOOL playerWins =
playerTapCount> opponentTapCount; - UIAlertView *endGameAlert
= [[UIAlertView
alloc]
initWithTitle: playerWins ? @"Victory!" : @"Defeat!" - message: playerWins ? @"Your thumbs have emerged
supreme!":
@"Your thumbs have been laid low" - delegate:nil
cancelButtonTitle:@"OK" - otherButtonTitles:nil]; [endGameAlert show];
- [endGameAlert release]; }
- -(void) endGame { opponentID =
nil; - startQuitButton.text = @"Find"; [gkSession disconnectFromAllPeers];
- [self showEndGameAlert]; }
- /*
- // The designated initializer. Override to perform setup
that is required before the view is loaded. -
(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle
*)nibBundleOrNil { - if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) { // Custom initialization
- } return self;
- } */
- /*
- // Implement loadView to create a view hierarchy programmatically, without using a nib. - (void)loadView {
- } */
- /*
- // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad {
- [super viewDidLoad]; }
- */
- /* // Override to allow orientations other than the default portrait orientation.
- -
(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{ // Return YES for supported orientations - return (interfaceOrientation == UIInterfaceOrientationPortrait); }
- */
- - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview.
- [super didReceiveMemoryWarning];
- // Release any cached data, images, etc that aren't in use. }
- - (void)viewDidUnload {
- // Release any retained subviews of the main view. // e.g.
self.myOutlet = nil; - }
- - (void)dealloc { [opponentID release];
- [playerTapCountLabel release]; [opponentTapCountLabel release];
- [startQuitButton release]; [gkSession release];
- [super dealloc]; }
[/pre]小结:iPhone开发之GameKit蓝牙实例讲解的内容介绍完 ,希望通过本文的学习能对你有所帮助!
[ios2]蓝牙通信【转】的更多相关文章
- Android学习笔记之蓝牙通信...
PS:最近同学问我蓝牙的事,因此自己也就脑补了一下蓝牙... 学习内容: 1.如何实现蓝牙通信技术... 蓝牙通信其实是手机里很常用的一种通信方式,现在的手机中是必然存在蓝牙的,蓝牙通信也是有一部 ...
- BLE蓝牙通信指令交互过程配对与绑定
最简单一次蓝牙通信需要以上相关步骤,包括discovery device,connect,pairing,bond等4个主要部分.BLE中主从机建立连接,到配对和绑定的过程如下图:
- Android -传统蓝牙通信聊天
概述 Android 传统蓝牙的使用,包括开关蓝牙.搜索设备.蓝牙连接.通信等. 详细 代码下载:http://www.demodashi.com/demo/10676.html 原文地址: Andr ...
- Android BLE设备蓝牙通信框架BluetoothKit
BluetoothKit是一款功能强大的Android蓝牙通信框架,支持低功耗蓝牙设备的连接通信.蓝牙广播扫描及Beacon解析. 关于该项目的详细文档请关注:https://github.com/d ...
- Android - 传统蓝牙通信聊天
Android -传统蓝牙通信聊天 技术:java+Android4.4+jdk1.8 运行环境:Android4.4.Android7.0 概述 Android 传统蓝牙的使用,包括开关蓝牙.搜索设 ...
- Android 串口蓝牙通信开发Java版本
Android串口BLE蓝牙通信Java版 0. 导语 Qt on Android 蓝牙通信开发 我们都知道,在物联网中,BLE蓝牙是通信设备的关键设备.在传统的物联网应用中,无线WIFI.蓝牙和Zi ...
- PC蓝牙通信C#代码实现
PC蓝牙通信C#代码实现 这篇文章主要为大家详细介绍了PC蓝牙通信C#代码实现,具有一定的参考价值,感兴趣的小伙伴们可以参考一下 本文实例为大家分享了C#实现PC蓝牙通信代码,供大家参考,具体内容如下 ...
- Android蓝牙通信总结
这篇文章要达到的目标: 1.介绍在Android系统上实现蓝牙通信的过程中涉及到的概念. 2.在android系统上实现蓝牙通信的步骤. 3.在代码实现上的考虑. 4.例子代码实现(手持设备和蓝牙串口 ...
- Qt on Android 蓝牙通信开发
版权声明:本文为MULTIBEANS ORG研发跟随文章,未经MLT ORG允许不得转载. 最近做项目,需要开发安卓应用,实现串口的收发,目测CH340G在安卓手机上非常麻烦,而且驱动都是Java版本 ...
随机推荐
- style、currentStyle、getComputeStylel的使用
(1)js中使用obj.style的用法,是为了获得内联样式,即style属性中的值. 如果想获取obj.style.display,但内联样式表中没有定义display,那么将返回一个空的字符串. ...
- rpt水晶报表制作过程
原文:rpt水晶报表制作过程 最近公司安排一个以前的项目,里面需要用到水晶报表,由于原来做这个项目的同事离职,所在公司的同事报表做成了rdlc类型的,而这类报表在加载的时候很难动态的从数据库加载数据, ...
- SufaceView(绘图类)
public class MainActivity extends Activity { GrameView grameView; @Override public void onCreate(Bun ...
- Date的使用
方法 说明 Date() 返回当日的日期和时间 getDate() 获取当天(1-31) getDay() 获取当天的星期(0-6) getMonth() 获取月份(0-11) getFullYear ...
- SHELL 近期学习
由于项目中很少使用到shell脚本所以.只是偶尔自学一点.慢慢积累.下面就把近段时间积累的发出来.学习. #sort sort 按首字母排序 sort -n 按数字大小 从小到大排序 sort -rn ...
- JavaScript实例技巧精选(10)—计算器实例2
>>点击这里下载完整html源码<< 这是截图: 利用Javascript和html实现的另一个计算器实例,核心代码如下: <script language=" ...
- JQuery UI Layout Plug-in布局
端]使用JQuery UI Layout Plug-in布局 引言 使用JQuery UI Layout Plug-in布局框架实现快速布局,用起来还是挺方便的,稍微研究了一下,就能上手,关于该布 ...
- 使用Eclipse开始Java编程
欢迎访问我的新博客:http://www.milkcu.com/blog/ 原文地址:http://www.milkcu.com/blog/archives/start-java-programing ...
- C#使用文件监控对象FileSystemWatcher 实现数据同步
在C#使用文件监控对象FileSystemWatcher 实现数据同步 2013-12-12 18:24 by 幕三少, 352 阅读, 3 评论, 收藏, 编辑 最近在项目中有这么个需求,就是得去实 ...
- D0
刚到长乐就被机房里众大神的气场给压倒了 orz....... 然后默默的感觉到自己貌似已经有一个星期没有打题了...就各种忧伤.... 还是说一下今天的计划吧 嗯傍晚5.30-6.00 &&a ...