#ifndef __CCPOMELO_H__
#define __CCPOMELO_H__
#include "cocos2d.h" json
class CCPomelo : public cocos2d::CCObject
{
public:
CCPomelo(){};
~CCPomelo(){}; ui
int connect(const char* addr, unsigned short port); spa
int request(const char* route, const char* msg); server
void onRequestCallback(int status, const char* msg); get
static CCPomelo* getInstance(); it
protected:
void* m_client; io
protected:
static CCPomelo* m_pInstance;
}; class
#endif cli
******************CCPomelo.cpp文件以下****************** route
#include "CCPomelo.h"
#include "pomelo.h"
USING_NS_CC;
CCPomelo* CCPomelo::m_pInstance = NULL;
CCPomelo* CCPomelo::getInstance()
{
if( !m_pInstance )
{
m_pInstance = new CCPomelo();
}
return m_pInstance;
}
void on_request_cb(pc_request_t *req, int status, json_t *resp) {
if(status == -1) {
//printf("Fail to send request to server.\n");
return;
} else if(status == 0) {
//printf("server response: %s\n", json_dumps(resp, 0));
}
// release relative resource with pc_request_t
json_t *msg = req->msg;
CCPomelo::getInstance()->onRequestCallback(status, json_dumps(msg, 0));
pc_request_destroy(req);
}
int CCPomelo::connect(const char* addr, unsigned short port)
{
m_client = pc_client_new();
struct sockaddr_in address;
memset(&address, 0, sizeof(struct sockaddr_in));
address.sin_family = AF_INET;
address.sin_port = htons(port);
address.sin_addr.s_addr = inet_addr(addr);
return pc_client_connect((pc_client_t*)m_client, &address);
}
void CCPomelo::onRequestCallback(int status, const char* msg)
{
CCLog(msg);
}
int CCPomelo::request(const char* route, const char* msg)
{
pc_request_t *request = pc_request_new();
json_error_t error;
return pc_request((pc_client_t*)m_client, request, route, json_loads(msg, 0, &error), on_request_cb);
}
而後導出到Js 能夠看 (coco2dx_root)/tools/tojs/README.mdown,詳細說明了如何導出Js
導出的時候我發現個問題,unsigned short port 導出Js的文件有問題 ,打開jsb_cocos2dx_extension_auto.cpp 加入jsval_to_uint16(cx,argv[1],&arg1);
最後腳本中調用:
cc.Pomelo.getInstance().connect("127.0.0.1", 3010); cc.Pomelo.getInstance().request("connector.helloHandler.hi", "{'msg' : 'hi~'}".replace(/'/g,"\""));