之前写了个接入game center的文章。
那么进入game center以后就需要后续的操作了。大部分的网络游戏都是用的socket长链接进行数据交换的。
之前也研究出来socket的连接方式了。可是昨天突然发现了一个php框架(WorkerMan)。是对webSocket进行的封装。感觉很强大。同时,cocos2d-x本身内置了webSocket的库。所以尝试着做了一下。
json用的不是cocos2d建议的rapidjson。而是用的jsoncpp。具体可以看himi的文章 http://www.himigame.com/iphone-cocos2dx/1492.html 。
因为rapidjson实在是太难用了。可能是我对c++的理解不到位,总之,我想封装一下,然后传个变量都做不到。
WebSocket无论是客户端,还是服务端的处理,都非常的简洁。而且据WorkerMan的作者说,进行过压力测试,数据非常好看。下面贴上今天整理的代码。
首先列出来我们用到的文件
AppDelegate.h
AppDelegate.mm
HelloWorldScene.h
HelloWorldScene.mm
JsonHelper.h
JsonHelper.cpp
GameKitHelper.mm
GameKitHelper.h
WorkerMan的官网如下 http://www.workerman.net
作者自己又对WorkerMan进行了封装。GateWorker。我现在用的是这个框架。更加适合用来开发游戏,而且封装了mysql数据库连接的库。
AppDelegate.h
#ifndef _APP_DELEGATE_H_
#define _APP_DELEGATE_H_
#include "cocos2d.h"
/**
@brief The cocos2d Application.
The reason for implement as private inheritance is to hide some interface call by Director.
*/
class AppDelegate : private cocos2d::Application
{
public:
AppDelegate();
virtual ~AppDelegate();
virtual void initGLContextAttrs();
/**
@brief Implement Director and Scene init code here.
@return true Initialize success, app continue.
@return false Initialize failed, app terminate.
*/
virtual bool applicationDidFinishLaunching();
/**
@brief The function be called when the application enter background
@param the pointer of the application
*/
virtual void applicationDidEnterBackground();
/**
@brief The function be called when the application enter foreground
@param the pointer of the application
*/
virtual void applicationWillEnterForeground();
};
#endif // _APP_DELEGATE_H_
AppDelegate.mm
#include "AppDelegate.h"
#include "HelloWorldScene.h"
#import "GameKitHelper.h"
USING_NS_CC;
AppDelegate::AppDelegate() {
}
AppDelegate::~AppDelegate()
{
}
//if you want a different context,just modify the value of glContextAttrs
//it will takes effect on all platforms
void AppDelegate::initGLContextAttrs()
{
//set OpenGL context attributions,now can only set six attributions:
//red,green,blue,alpha,depth,stencil
GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8};
GLView::setGLContextAttrs(glContextAttrs);
}
bool AppDelegate::applicationDidFinishLaunching() {
[[GameKitHelper sharedGameKitHelper] authenticateLocalUser];
// initialize director