`
dongyafeiying
  • 浏览: 5027 次
  • 性别: Icon_minigender_1
  • 来自: 济南
社区版块
存档分类
最新评论

蓝牙实例

阅读更多
转载自:http://www.aisidachina.com

原创文章:http://www.aisidachina.com/forum/thread-134-1-1.html 转载请注明出处

介绍一下这个实例实现的是两个带有蓝牙设备的touch之间的一个小游戏,在界面上有个可以响应事件的UIView(之前说过)可以点击,然后看谁新达到WINNING_TAP_COUNT (游戏中一常量可以自己设置)谁先达到谁就赢了,然后通知对方。还要引入GameKit.framework框架
头文件BlueToothViewController.h:

//
//
// 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



下面是BlueToothViewController.m:



//
// BlueToothViewController.m
// BlueTooth
//
// Created by mingchun liu on 09-11-24.
// Copyright sdie 2009. All rights reserved.
//
#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 {
        playerTapCount = 0;
        opponentTapCount = 0;
}
-(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];
}

分享到:
评论

相关推荐

    Android蓝牙实例

    通过Android蓝牙实例,我们可以深入了解如何在Android应用中实现蓝牙的各种功能,包括开启、关闭、搜索等。下面将详细介绍这些知识点。 首先,开启和关闭蓝牙是Android应用中最基本的操作。在Android中,我们使用`...

    官方蓝牙实例

    【蓝牙实例】是一种官方提供的蓝牙通信技术应用案例,主要用于设备之间的数据传输。在小程序的开发中,蓝牙功能常被用于实现物联网(IoT)场景,比如智能硬件的控制、健康监测设备的数据同步等。这个实例可能包含了一...

    android连接蓝牙实例

    在Android平台上实现蓝牙连接并操作蓝牙读卡器的过程涉及到多个技术环节,包括蓝牙适配器的检测、设备的扫描与连接、数据传输以及读卡命令的发送与接收。以下是对这些知识点的详细说明: 1. **蓝牙适配器的检测**:...

    APP蓝牙Demo.zip_settinglyb_uniapp 开发app_蓝牙_蓝牙 uni_跨平台蓝牙demo

    标题“APP蓝牙Demo.zip_settinglyb_uniapp 开发app_蓝牙_蓝牙 uni_跨平台蓝牙demo”表明这是一个关于使用uni-app开发的项目,其中包含了蓝牙功能的实现,特别强调了自动开启蓝牙的能力,以及其跨平台的特性。...

    蓝牙演示实例——MoveBoxs

    【蓝牙实例——MoveBoxs】 MoveBoxs是一个蓝牙通信的示例项目,它展示了如何在实际应用中使用蓝牙技术。这个实例包括了蓝牙的创建、数据传输、连接的销毁以及连接异常处理等关键步骤。 1. **蓝牙创建**:在应用...

    蓝牙搜索实例bleTester.rar

    标题“蓝牙搜索实例bleTester.rar”指的是一个包含蓝牙搜索功能的安卓应用示例程序,而“安卓查找蓝牙 搜索蓝牙实例程序”的描述进一步确认了这是一个用于演示如何在Android平台上实现蓝牙搜索功能的应用。...

    经典蓝牙+ble蓝牙(低功耗蓝牙)客户端\服务端开发

    在IT行业中,蓝牙技术是一种广泛应用于无线通信的短距离传输技术,主要分为经典蓝牙和BLE(低功耗蓝牙)两种类型。本主题聚焦于这两种蓝牙技术的客户端和服务端开发,特别是针对Android平台。 经典蓝牙是一种早期的...

    MI wristband Bluetooth real Project (小米手环蓝牙实例项目 ).zip

    1. **设备连接与数据同步**:源码具备高效稳定的蓝牙连接模块,可实现实时、准确的手环与手机之间的数据同步,包括运动步数、心率、睡眠质量等健康监测数据。 2. **全面健康监测**:内置丰富的健康算法模型,支持对...

    Android实例-Delphi开发蓝牙官方实例解析(XE10+小米2+小米5)

    本文将基于Delphi XE10,结合小米2和小米5设备,深入探讨如何利用Delphi进行Android蓝牙功能的开发,提供一个实用的实例解析。 首先,我们要明确的是,蓝牙技术在移动设备间的数据传输中扮演着重要角色,尤其在...

    青风的蓝牙工程实例【包含详细讲解】

    青风的蓝牙工程实例课程是针对蓝牙技术的深入学习资源,涵盖了从基础理论到实际应用的全面知识。在这个实例教程中,青风讲师通过详细讲解蓝牙工程的各种应用场景和实现方式,帮助学习者理解和掌握蓝牙技术的最新发展...

    微信公众号蓝牙连接php实现(原生)

    微信公众号蓝牙连接php实现(原生) . /*此代码仅做参考 , 具体还需多加尝试,当时历时一周才做出来,有些内容需要和硬件开发者沟通 , 比如连接规则.*/

    linux DBUS 实例讲解

    ### Linux DBUS 实例讲解 #### 一、DBUS 是什么? D-Bus是一种轻量级的进程间通信(IPC)机制,专为Linux和其他类Unix操作系统设计,主要用于桌面环境中不同应用程序之间的通信以及应用程序与系统内核之间的通信。相...

    android蓝牙通信实例

    本文将深入探讨如何在Android中实现蓝牙通信,基于提供的"android蓝牙通信实例",我们将详细解析这一过程。 首先,我们要了解Android蓝牙通信的基础。Android支持两种蓝牙模式:经典蓝牙(Classic Bluetooth)和低...

    Android的蓝牙编程例子 完整源码下载

    在Android平台上进行蓝牙编程是一项常见的任务,特别是在物联网(IoT)和移动设备交互的应用中。本文将深入探讨如何使用Android的Bluetooth API进行SPP(Serial Port Profile)协议的蓝牙通信,以便与支持此协议的串口...

    xamarin android c# 蓝牙源码

    xamarin android c# 蓝牙源码 在vs2010上编通过 可以跟蓝牙模块通信,

    C# 蓝牙通讯实例

    在本案例中,"C# 蓝牙通讯实例"是关于如何利用C#进行蓝牙设备之间的通信实现,这对于创建无线连接的应用程序,如文件传输、设备控制等场景非常实用。以下是关于这个主题的详细知识: ### 1. 蓝牙技术概述 蓝牙是一...

    蓝牙鼠标程序(蓝牙技术鼠标应用实例)

    在这个实例中,我们专注于蓝牙技术在鼠标中的应用,这对于初学者来说是一个很好的学习案例。 首先,我们要理解蓝牙鼠标的核心工作原理。蓝牙鼠标通过蓝牙适配器与计算机建立连接,这个适配器可以内置在笔记本电脑或...

    蓝牙通讯实例

    蓝牙通讯实例是一个典型的移动设备间通信技术应用,主要利用了蓝牙技术进行数据交换。蓝牙是一种短距离无线通信技术,允许电子设备在一定范围内(通常10米)建立连接,进行数据传输。在这个实例中,我们将关注如何在...

    Android蓝牙程序实例

    本文将详细解析"Android蓝牙程序实例",帮助你深入了解如何在Android Studio环境中开发蓝牙应用。 首先,Android蓝牙编程主要依赖于`BluetoothAdapter`、`BluetoothDevice`、`BluetoothSocket`和`...

    Android 蓝牙BLE全面解析以及智能车锁开发实例

    Android 蓝牙BLE全面解析以及智能车锁开发实例一、蓝牙BLE产生背景——蓝牙的发展历程 二、蓝牙BLE的基本概念 三、蓝牙BLE的架构介绍 1. 蓝牙BLE架构概览 2. 简述BLE如何发送数据包 2.1 广播方式 2.2 连接方式 四、...

Global site tag (gtag.js) - Google Analytics