1.httpClient和ScrollView

1 在服务器端使用sqllite编写数据库

常见命令是:sqlite3 tank.db


进入之后创建表:

create table tscore (

id integer primary key autoincrement,

username varchar(32) unique not null,

totalscore integer not null,

score integer not null

);


在服务器端编写程序:

#include<stdio.h>

#include<sqlite3.h>

#include<string.h>

#include<stdlib.h>

 

int main()

     printf("Content-type:text/html\n\n");

     //set Score to Database

     char * queryString = getenv("QUERY_STRING");

     if(queryString == NULL)

     {

         printf("Err:queryString is NULL");

         return 0;

     }

 

     //totalscore=%d&score=%d&user=user%d

     //获取参数

     char *totalScore = strtok(queryString,"&");

     char *score = strtok(NULL,"&");

     char *username = strtok(NULL,"&");

 

     strtok(totalScore,"=");

     totalScore = strtok(NULL,"=");

 

     strtok(score,"=");

     score = strtok(NULL,"=");

 

     //写数据库

     sqlite3* db;

     int ret = sqlite3_open("/usr/lib/cgi-bin/tank.db",&db);

     if(ret != SQLITE_OK)

     {

         printf("open database error:%s",sqlite3_errstr(sqlite3_errcode(db)));

         return 0;

     }

 

     char sql[2048];

     sprintf(sql,"insert into tscore(username,totalScore,score) values(‘%s‘,%s,%s)",usernam|      e,totalScore,score);

     ret = sqlite3_exec(db,sql,NULL,NULL,NULL);

     printf("%s<br>",sql);

 

     if(ret != SQLITE_OK)

     {

printf("insert data error:%s",sqlite3_errstr(sqlite3_errcode(db)));

         sqlite3_close(db);

         return 0;

     }

 

     return 0;

}

编译:

sudo gcc setScore.c -o setScore.cgi -lsqlite3

注意要加上最后面的-lsqlite3,不然

设置tank.db的权限


在浏览器中输入以下链接地址:

http://192.168.28.155/cgi-bin/setScore.cgi?totalscore=100&score=1011&username=toto

网页中的输出运行结果:


tank.db中的内容如下:


2 游戏服务器端代码,用于操作数据库

 

#include <stdio.h>

#include <sqlite3.h>

#include <string.h>

#include <stdlib.h>

int selectCallback(void* arg,int argc,char** argv,char** argvv)

{

    //argv[0] id

    //argv[1] username

    //argv[2] totalscore

    //argv[3] score

 

    // username&totalscore&score&....

    printf("%s&%s&%s&", argv[1], argv[2], argv[3]);

    return 0;

}

 

int main()

{

    printf("Content-type:text/html\n\n");

#if 0

    printf("This is cocos cgi-test\n");

    // 打印环境变量

    extern char** environ;

    int i;

    for(i=0; ;++i)

    {

        if(environ[i])

            printf("%s\n<br>", environ[i]);

        else

            break;

    }

#endif

 

    // set Score to Database

    char* queryString = getenv("QUERY_STRING");

    if(queryString == NULL)

    {

        printf("Err: queryString is NULL");

        return 0;

    }

 

    // totalscore=%d&score=%d&user=user%d

    // 获取参数

    char* totalScore = strtok(queryString, "&");

    char* score = strtok(NULL, "&");

    char* username = strtok(NULL, "&");

 

    strtok(totalScore, "=");

    totalScore = strtok(NULL, "=");

 

    strtok(score, "=");

    score = strtok(NULL, "=");

 

    strtok(username, "=");

    username = strtok(NULL, "=");

 

    // 写数据库

    sqlite3* db;

    int ret = sqlite3_open("/usr/lib/cgi-bin/tank.db", &db);

    if(ret != SQLITE_OK)

    {

        printf("open database error: %s", sqlite3_errstr(sqlite3_errcode(db)));

        return 0;

    }

 

    char sql[2048];

    sprintf(sql, "insert into tscore (username, totalscore, score) values (‘%s‘, %s, %s)",

            username, totalScore, score);

    ret = sqlite3_exec(db, sql, NULL, NULL, NULL);

#if 0

    printf("%s<br>", sql);

    return 0;

#endif

    if(ret != SQLITE_OK)

    {

        printf("insert data error: %s", sqlite3_errstr(sqlite3_errcode(db)));

        sqlite3_close(db);

        return 0;

    }

 

    sprintf(sql, "select * from tscore order by totalscore desc limit 10");

    ret = sqlite3_exec(db, sql, selectCallback, NULL, NULL);

    if(ret != SQLITE_OK)

    {

        printf("select data error: %s", sqlite3_errstr(sqlite3_errcode(db)));

        sqlite3_close(db);

        return 0;

    }

 

    sqlite3_close(db);

 

    return 0;

}

Makefile文件

cfiles := $(shell find -name "*.c")

targets := $(cfiles:.c=.cgi)

 

all: $(targets)

 

%.cgi:%.c

         gcc -o $@ $^ -lsqlite3

 

.PHONY: clean

clean:

         rm *.cgi

编译:

sudo gcc setScore.c -o setScore.cgi -lsqlite3

浏览器访问:

http://192.168.28.155/cgi-bin/setScore.cgi?totalscore=90&score=121&username=toto23


 

较完整的服务器段代码

setScore.c

 

#include <stdio.h>

#include <sqlite3.h>

#include <string.h>

#include <stdlib.h>

int selectCallback(void* arg,int argc,char** argv,char** argvv)

{

    //argv[0] id

    //argv[1] username

    //argv[2] totalscore

    //argv[3] score

 

    // username&totalscore&score&....

    printf("%s&%s&%s&", argv[1], argv[2], argv[3]);

    return 0;

}

 

int main()

{

    printf("Content-type:text/html\n\n");

#if 0

    printf("This is cocos cgi-test\n");

    // 打印环境变量

    extern char** environ;

    int i;

    for(i=0; ;++i)

    {

        if(environ[i])

            printf("%s\n<br>", environ[i]);

        else

            break;

    }

#endif

 

    // set Score to Database

    char* queryString = getenv("QUERY_STRING");

    if(queryString == NULL)

    {

        printf("Err: queryString is NULL");

        return 0;

    }

 

    // totalscore=%d&score=%d&user=user%d

    // 获取参数

    char* totalScore = strtok(queryString, "&");

    char* score = strtok(NULL, "&");

    char* username = strtok(NULL, "&");

 

    strtok(totalScore, "=");

    totalScore = strtok(NULL, "=");

 

    strtok(score, "=");

    score = strtok(NULL, "=");

 

    strtok(username, "=");

    username = strtok(NULL, "=");

 

    // 写数据库

    sqlite3* db;

    int ret = sqlite3_open("/usr/lib/cgi-bin/tank.db", &db);

    if(ret != SQLITE_OK)

    {

        printf("open database error: %s", sqlite3_errstr(sqlite3_errcode(db)));

        return 0;

    }

 

    char sql[2048];

    sprintf(sql, "insert into tscore (username, totalscore, score) values (‘%s‘, %s, %s)",

            username, totalScore, score);

    ret = sqlite3_exec(db, sql, NULL, NULL, NULL);

#if 0

    printf("%s<br>", sql);

    return 0;

#endif

    if(ret != SQLITE_OK)

    {

        printf("insert data error: %s", sqlite3_errstr(sqlite3_errcode(db)));

        sqlite3_close(db);

        return 0;

    }

 

    sprintf(sql, "select * from tscore order by totalscore desc limit 10");

    ret = sqlite3_exec(db, sql, selectCallback, NULL, NULL);

    if(ret != SQLITE_OK)

    {

        printf("select data error: %s", sqlite3_errstr(sqlite3_errcode(db)));

        sqlite3_close(db);

        return 0;

    }

    sqlite3_close(db);

    return 0;

}

 

3 HttpClient的客户端:

T24HttpClient.h(Get方式)

#ifndef __T24HttpClient_H__

#define __T24HttpClient_H__

 

#include "cocos2d.h"

#include "cocos-ext.h"

#include "TBack.h"

USING_NS_CC;

USING_NS_CC_EXT;

 

class T24HttpClient :public TBack

{

public:

    CREATE_FUNC(T24HttpClient);

    bool init();

    static CCScene * scene();

 

    void HttpResponse(CCHttpClient* client, CCHttpResponse* response);

};

 

#endif

T24HttpClient.cpp

#include "T24HttpClient.h"

 

CCScene* T24HttpClient::scene()

{

    CCScene* scene = CCScene::create();

    T24HttpClient* layer = T24HttpClient::create();

    scene->addChild(layer);

    return scene;

}

 

bool T24HttpClient::init()

{

    TBack::init();

   

    //向服务器发送请求(http报文)单例

    CCHttpClient* client = CCHttpClient::getInstance();

   

    //创建一个request对象

    CCHttpRequest* request = new CCHttpRequest();

    //设置访问URL

    request->setUrl("http://192.168.192.130/cgi-bin/setScore.cgi?username=xxx&score=xxxx&totalscore=xxx");

    request->setResponseCallback(this, httpresponse_selector(T24HttpClient::HttpResponse));

 

    //要对client进行release

    client->release();

 

    return true;

}

 

//通过回调的方式实现

void T24HttpClient::HttpResponse(CCHttpClient* client, CCHttpResponse* response)

{

    if (!response->isSucceed())

    {

        CCLog("response error: %s", response->getErrorBuffer());

        return;

    }

 

    //获得相应的数据

    std::vector<char>* data = response->getResponseData();

 

    std::string strData;

    std::vector<char>::iterator it;

    for (it = data->begin(); it != data->end(); ++it)

    {

        strData.push_back(*it);

    }

 

    CCLog("response data is: %s", strData.c_str());

}

运行结果:

 

HttpClient(POST方式);

#ifndef __HttpClientPost_H__

#define __HttpClientPost_H__

 

#include "cocos2d.h"

#include "cocos-ext.h"

#include "TBack.h"

USING_NS_CC;

USING_NS_CC_EXT;

 

class HttpClientPost:public TBack

{

public:

    CREATE_FUNC(HttpClientPost);

    bool init();

    static CCScene* scene();

 

    void HttpResponse(CCHttpClient* client, CCHttpResponse* response);

};

 

#endif

HttpClientPost.cpp

#include "HttpClientPost.h"

 

CCScene* HttpClientPost::scene()

{

    CCScene* scene = CCScene::create();

    HttpClientPost* layer = HttpClientPost::create();

    scene->addChild(layer);

    return scene;

}

 

bool HttpClientPost::init()

{

    TBack::init();

    //向服务器发送请求(http报文)

    CCHttpClient* client = CCHttpClient::getInstance();

 

    CCHttpRequest* req = new CCHttpRequest;

    req->setUrl("http://192.168.192.131/cgi-bin/posttest.cgi");

    req->setRequestType(CCHttpRequest::kHttpPost);

    req->setResponseCallback(this, httpresponse_selector(HttpClientPost::HttpResponse));

 

    char buf[8192];

 

    FILE* f = fopen("btn_go_0.png","rb");

    int len = fread(buf,1,8192,f);

    fclose(f);

    CCLOG("len=%d\n",len);

 

    req->setRequestData((const char*)buf,len);

 

    client->send(req);

    req->release();

 

    return true;

}

 

void HttpClientPost::HttpResponse(CCHttpClient* client, CCHttpResponse* response)

{

    //如果相应失败

    if (!response->isSucceed())

    {

        //获取失败信息

        CCLog("response error: %s", response->getErrorBuffer());

        return;

    }

   

    //获得相应的数据

    std::vector<char>* data = response->getResponseData();

 

    std::string strData;

    std::vector<char>::iterator it;

    for (it = data->begin(); it != data->end(); ++it)

    {

        strData.push_back(*it);

    }

 

    CCLog("response data is:%s", strData.c_str());

}

运行结果:

 

 

 

2 CCScrollView案例

T25ScrollView.h

#ifndef __T25ScrollView_H__

#define __T25ScrollView_H__

 

#include "cocos2d.h"

#include "cocos-ext.h"

#include "TBack.h"

USING_NS_CC;

USING_NS_CC_EXT;

 

class T25ScrollView :public TBack

{

public:

    CREATE_FUNC(T25ScrollView);

    bool init();

    static CCScene * scene();

 

    bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent);

    void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent);

    void adjustViewPos(float dt);

 

    CCNode* _node;

    bool isSlider(CCTouch* t);

};

 

#endif

T25ScrollView.cpp

#include "T25ScrollView.h"

 

CCScene *T25ScrollView::scene()

{

    CCScene * scene = CCScene::create();

    T25ScrollView * layer = T25ScrollView::create();

    scene->addChild(layer);

    return scene;

}

 

bool T25ScrollView::init()

{

    TBack::init();

 

    CCSize winSize = CCDirector::sharedDirector()->getWinSize();

 

    CCNode* node = CCNode::create();

    _node = node;

    char buf[] = "a";

    //注意:ScrollView中的每个元素实际上都是一个精灵

    for (int i = 0; i < 5; ++i)

    {

        //创建精灵

        CCSprite* s = CCSprite::create("HelloWorld.png");

        //将精灵添加到node中去

        node->addChild(s);

        s->setPosition(ccp(0, winSize.height*i));

        s->setAnchorPoint(ccp(0, 0));

 

        //设置标签

        CCLabelTTF* label = CCLabelTTF::create(buf, "Arial", 24);

        buf[0]++;

        s->addChild(label);

        label->setPosition(ccp(winSize.width / 2, winSize.height / 2));

    }

 

    //创建ScrollView,创建的时候需要node节点

    CCScrollView* view = CCScrollView::create(winSize, node);

    addChild(view);

    //设置滚动试图的显示方式,下面的设置表示的是垂直滚动

    view->setDirection(kCCScrollViewDirectionVertical);

    //设置view的ContentSize,大小是5个精灵的高度

    view->setContentSize(CCSizeMake(winSize.width, winSize.height * 5));

    view->setBounceable(false);// 去掉弹性

 

    setTouchEnabled(true);

    setTouchMode(kCCTouchesOneByOne);

 

    return true;

}

 

bool T25ScrollView::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)

{

    return true;

}

 

//判断是否滚动了

bool T25ScrollView::isSlider(CCTouch* t)

{

    CCPoint ptCur = t->getLocation();

    CCPoint ptStart = t->getStartLocation();

    if (ptCur.getDistanceSq(ptStart) > 25)

    {

        return true;

    }

    return false;

}

 

void T25ScrollView::adjustViewPos(float dt)

{

    //计算

    CCSize winSize = CCDirector::sharedDirector()->getWinSize();

    int fitPos[] = {

        0,                     

        -winSize.height,       //向下移动一屏

        -winSize.height * 2,   //向下移动两屏

        -winSize.height * 3,   //向下移动三屏

        -winSize.height * 4    //向下移动四屏

    };

 

    int y = _node->getPositionY();

    int i;

    for (i = 0; i < 5; ++i)

    {

        int dist = abs(fitPos[i] - y);

        if (dist < winSize.height / 2)

        {

            break;

        }

    }

 

    //创建一个点

    CCPoint ptDest = ccp(0, fitPos[i]);

    //让点移动到指定的位置

    _node->runAction(CCMoveTo::create(.2f, ptDest));

}

 

void T25ScrollView::ccTouchEnded(CCTouch* t, CCEvent* e)

{

    //判断点击的坐标,是哪个坐标

    if (isSlider(t))

    {

        //调整位置

        scheduleOnce(schedule_selector(T25ScrollView::adjustViewPos), 0.05f);

        return;

    }

 

    //点击的代码

    CCSize winSize = CCDirector::sharedDirector()->getWinSize();

 

    CCPoint ptWorld = t->getLocation();

    //将世界坐标转化成为本地坐标

    CCPoint ptNode = _node->convertToNodeSpace(ptWorld);

    int index = ptNode.y / winSize.height;

    CCLog("clicked index=%d", index);

}

运行结果(上下移动):


 

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。