首先.从github上把pomelo-ios Client (https://github.com/NetEase/pomelo-iosclient)下载下来,并且将其依赖的第三方库socket.io-Objc和SocketRocket一并下载下来。
然后.新建一个Cocos2d的xcode项目,将这三个库的文件导入。并且将SocketRocket依赖的lib添加进来。
相信做过pomelo的iOS客户端的这两步很easy。如果这两步有什么问题可以在这片博文下问我。在我写这篇博文的时候SocketRocket暂时还部支持iOS6,所以项目的development target 建议设为5.1
接下来是把pomelo放到AppDelegate里面
AppDelegate.h
#import <UIKit/UIKit.h>
#import "Pomelo.h"
@class RootViewController;
@interface AppDelegate : NSObject <UIApplicationDelegate,PomeloDelegate> {
UIWindow *window;
RootViewController *viewController;
}
@property (nonatomic) UIWindow *window;
@property (strong, nonatomic) Pomelo *pomelo;
@end
AppDelegate.m
这个文件代码太多,就只贴添加的两行代码。由于Cocos2d中的Layer不能做alloc,init操作,所以不能像iOS Client那样在AppDelegate中把pomelo赋给一个Controller,然后一个个Controller相互把传递传递下去(因为一个工程只能有pomelo实例,你可以把pomelo看成单例,但是网易没有设计成单例,考虑到以后可能会有多个实例的设计,记住,pomelo只要实例化一次就好)
@synthesize pomelo;
在applicationDidFinishLaunching中
pomelo = [[Pomelo alloc] initWithDelegate:self];
然后在Layer中就可以直接实例化然后发送请求。
也需要#import @property之类的把pomelo文件先导进来
实例化:
AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
pomelo = myDelegate.pomelo;
[pomelo connectToHost:@"127.0.0.1" onPort:3014 withCallback:^(Pomelo *p){
NSLog(@"after connectToHost------------");
NSDictionary *params = [NSDictionary dictionaryWithObject:@"chenyl107" forKey:@"uid"];
[pomelo requestWithRoute:@"gate.gateHandler.queryEntry" andParams:params andCallback:^(NSDictionary *result){
NSLog(@"after gate-----------");
[pomelo disconnectWithCallback:^(Pomelo *p){
// [self entryWithData:result];
host = [result objectForKey:@"host"];
port = [[result objectForKey:@"port"] intValue];
NSLog(@"%@",host);
NSLog(@"%d",port);
//连接得到的connection服务器
[pomelo connectToHost:host onPort:port withCallback:^(Pomelo *p){
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
name, @"username",
channel, @"rid",
nil];
[p requestWithRoute:@"connector.entryHandler.enter" andParams:params andCallback:^(NSDictionary *result){
NSArray *userList = [result objectForKey:@"users"];
for (NSString *name1 in userList) {
NSLog(@"%@",name1);
//只是为了看一下该频道里有多少人
}
}];
}];
}];
}];
}];
简单分析下:connectToHost是与服务器建立长连接,建立好后发送一个request请求到gate服务器,gate服务器将分配给用户的connect服务器的host,port发送给客户端,客户端这个时候要断开与gate的连接,然后去连接connect服务器,然后对connect服务器发送一个request请求。然后接受connect返回的数据。
等过了期末考试再总结下从一个pomelo新建的helloworld程序怎么完善成一个从数据库到服务器再到客户端的完整的小小小demo。待续。。。。